pax_global_header00006660000000000000000000000064120772374640014526gustar00rootroot0000000000000052 comment=9a1a6d1b36889df96ba375a1ccc32ed19263a2e0 lua-cosmo-13.01.30/000077500000000000000000000000001207723746400136525ustar00rootroot00000000000000lua-cosmo-13.01.30/Makefile000066400000000000000000000021471207723746400153160ustar00rootroot00000000000000# $Id: Makefile,v 1.1.1.1 2007/11/26 17:12:24 mascarenhas Exp $ config_file:=config ifneq '$(wildcard $(config_file))' '' include $(config_file) endif $(config_file): chmod +x configure all: install: $(config_file) mkdir -p $(LUA_DIR) mkdir -p $(LUA_DIR)/cosmo cp src/cosmo.lua $(LUA_DIR)/ cp src/cosmo/grammar.lua $(LUA_DIR)/cosmo cp src/cosmo/fill.lua $(LUA_DIR)/cosmo install-rocks: install mkdir -p $(PREFIX)/samples cp -r samples/* $(PREFIX)/samples mkdir -p $(PREFIX)/doc cp -r doc/* $(PREFIX)/doc mkdir -p $(PREFIX)/tests cp -r tests/* $(PREFIX)/tests echo "Go to $(PREFIX) for samples and docs!" test: cd tests && lua -l luarocks.require test_cosmo.lua upload-cvs: git archive --format=tar --prefix=cosmo-current/ master | gzip > cosmo-current.tar.gz ncftpput -u mascarenhas ftp.luaforge.net cosmo/htdocs cosmo-current.tar.gz upload-dist: git archive --format=tar --prefix=cosmo-$(VERSION)/ v$(VERSION) | gzip > cosmo-$(VERSION).tar.gz ncftpput -u mascarenhas ftp.luaforge.net cosmo/htdocs cosmo-$(VERSION).tar.gz ncftpput -u mascarenhas ftp.luaforge.net cosmo/htdocs doc/index.html clean: lua-cosmo-13.01.30/Makefile.win000066400000000000000000000012341207723746400161060ustar00rootroot00000000000000# $Id: Makefile,v 1.1.1.1 2007/11/26 17:12:24 mascarenhas Exp $ LUA_INCLUDE= c:\lua5.1\include LUA_LIB= c:\lua5.1\lua5.1.lib LUA_DIR= c:\lua5.1\lua LUA_LIBDIR= c:\lua5.1 all: install: IF NOT EXIST "$(LUA_DIR)\cosmo" mkdir "$(LUA_DIR)\cosmo" copy src\cosmo.lua "$(LUA_DIR)\" copy src\cosmo\grammar.lua "$(LUA_DIR)\cosmo" copy src\cosmo\fill.lua "$(LUA_DIR)\cosmo" install-rocks: install IF NOT EXIST "$(PREFIX)\samples" mkdir "$(PREFIX)\samples" IF NOT EXIST "$(PREFIX)\doc" mkdir "$(PREFIX)\doc" IF NOT EXIST "$(PREFIX)\tests" mkdir "$(PREFIX)\tests" xcopy /E samples "$(PREFIX)\samples\" xcopy /E doc "$(PREFIX)\doc\" xcopy /E tests "$(PREFIX)\tests\" lua-cosmo-13.01.30/README000066400000000000000000000014461207723746400145370ustar00rootroot00000000000000Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. The current version of Cosmo is 13.01.30. This release adds Lua 5.2 support. The previous version, 10.04.06, added, expressions to selectors $(), allowed nested [[ ]] in templates, made commas between subtemplates optional, and added a second parameter to cosmo.yield that tells Cosmo the first parameter is a literal to be included in the expansion instead of an environment. Cosmo is installed as a rock. To install the most recent release do `luarocks install cosmo`. The Cosmo rock is in the standard repository. Installation on UNIX-based systems need the gcc toolchain. lua-cosmo-13.01.30/configure000077500000000000000000000014161207723746400155630ustar00rootroot00000000000000#!/bin/bash if [ $1 == "--help" ]; then echo "Usage: configure lua51" echo "where lua51 is the name of your Lua executable" exit 0 fi echo "Trying to find where you installed Lua..." if [ $1 != "" ]; then lua=$1 else lua="lua51" fi lua_bin=`which $lua` lua_bin_dir=`dirname $lua_bin` lua_root=`dirname $lua_bin_dir` if [ $lua_root != "" ]; then echo "Lua is in $lua_root" echo "Writing config" lua_share=$lua_root/share/lua/5.1 lua_lib=$lua_root/lib/lua/5.1 bin_dir=$lua_root/bin echo "LUA_BIN= $lua_bin" > config echo "LUA_DIR= $lua_share" >> config echo "BIN_DIR= $bin_dir" >> config echo "LUA_LIBDIR= $lua_lib" >> config echo "Now run 'make && sudo make install'" else echo "Lua not found, please install Lua 5.1 (and put in your PATH)" fi lua-cosmo-13.01.30/doc/000077500000000000000000000000001207723746400144175ustar00rootroot00000000000000lua-cosmo-13.01.30/doc/cosmo.md000066400000000000000000000434771207723746400161000ustar00rootroot00000000000000 Cosmo Overview ================================================= Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. Installation ================================================= The current version of Cosmo is 13.01.30. This release adds Lua 5.2 support. The previous version, 10.04.06, added, expressions to selectors $(\), allowed nested \[\[ \]\] in templates, made commas between subtemplates optional, and added a second parameter to cosmo.yield that tells Cosmo the first parameter is a literal to be included in the expansion instead of an environment. Cosmo is installed as a rock. To install the most recent release do `luarocks install cosmo`. The Cosmo rock is in the standard repository. Installation on UNIX-based systems need the gcc toolchain. Using Cosmo ================================================= ## Simple Form Filling Let's start with a simple example of filling a set of scalar values into a template: Here are a few examples of Cosmo in use: > values = { rank="Ace", suit="Spades" } > template = "$rank of $suit" > require("cosmo") > = cosmo.fill(template, values) Ace of Spades Note that the template is a string that marks where values should go. We call a template variable like `$rank` a *selector*, and `rank` is the selector's name. The table passed to `cosmo.fill` is the *environment*, and it provides the values. `$rank` will get replaced by `value.rank` ("Ace") and `$suit` will get replaced by `value.suit` ("Spades"). `cosmo.fill` takes two parameters at once. Cosmo also provides a "shortcut" method `f()` which takes only one parameter - the template - and returns a function that then takes the second parameter. This allows for a more compact notation: > = cosmo.f(template){ rank="Ace", suit="Spades" } Ace of Spades A selector can be either a string or a Lua expression in parenthesis, like `$("foo" .. "bar")` is replaced by `foobar` in the template. Any variables in the expression are looked-up in the current template environment, so `$(foo)` is the same as `$foo`, and `$(rank .. suit)` would be replaced by `AceSpades` in the previous example. ## Nested Values You aren't restricted to scalar values; your values can be Lua tables that you can destructure using a *$val|key1|key2|...|keyn* syntax. For example: > values = { cards = { { rank = "Ace" , suit = "Spades" } } } > template = "$cards|1|rank of $cards|1|suit" > = cosmo.fill(template, values) Ace of Spades As you can see above, you can either use numbers or strings as keys. ## Arguments You can also pass arguments to a selector using the syntax *$selector{ args }*. The syntax for the argument list is the same as a Lua table constructor, but function definitions are not allowed, and you can use template selectors, which are looked up in the template environment. If you pass an argument list and the selector maps to a function then Cosmo calls this function with the argument list as a table, and the selector expands to what the function returns. For example: > values = { message = function (arg) return arg.rank .. " of " .. arg.suit end } > template = "$message{ rank = 'Ace', suit = 'Spades' }" > = cosmo.fill(template, values) Ace of Spades ## Subtemplates Now, suppose we have not just one card, but several. Cosmo allows us to handle this case with "subtemplates" > mycards = { {rank="Ace", suit="Spades"}, {rank="Queen", suit="Diamonds"}, {rank="10", suit="Hearts"} } > template = "$do_cards[[$rank of $suit, ]]" > = cosmo.fill(template, {do_cards = mycards}) Ace of Spades, Queen of Diamonds, 10 of Hearts, The subtemplate "$rank or $suit" could be enclosed in `[[...]]`, `[=[...]=]`, `[==[...]==]`, etc. - just like Lua's long-quoted strings. Again, we can use the shortcut `f()`: > = cosmo.f(template){do_cards = mycards} Ace of Spades, Queen of Diamonds, 10 of Hearts, ## Subtemplates with Functions If we don't have a ready table that would match the template, we can set the value of `do_cards` to a function, which will yield a set of values for the subtemplate each time it's called: > mycards = { {"Ace", "Spades"}, {"Queen", "Diamonds"}, {"10", "Hearts"} } > = cosmo.f(template){ do_cards = function() for i,v in ipairs(mycards) do cosmo.yield{rank=v[1], suit=v[2]} end end } Ace of Spades, Queen of Diamonds, 10 of Hearts, You can also pass a list of arguments to this function: > template = "$do_cards{ true, false, true }[[$rank of $suit, ]]" > mycards = { {"Ace", "Spades"}, {"Queen", "Diamonds"}, {"10", "Hearts"} } > = cosmo.f(template){ do_cards = function(arg) for i,v in ipairs(mycards) do if arg[i] then cosmo.yield{rank=v[1], suit=v[2]} end end end } Ace of Spades, 10 of Hearts, Finally, you can pass a literal to be included in the expansion instead of an environment. An example: > template = "$do_cards{ true, false, true }[[$rank of $suit]]" > mycards = { {"Ace", "Spades"}, {"Queen", "Diamonds"}, {"10", "Hearts"} } > = cosmo.f(template){ do_cards = function(arg) local n = #mycards for i,v in ipairs(mycards) do cosmo.yield{rank=v[1], suit=v[2]} if i < n then cosmo.yield(", ", true) end end end } Ace of Spades, Queen of Diamonds, 10 of Hearts ## Alternative Subtemplates In some cases we may want to use differente templates for different items in the list. For example, we might want to use a different template for the first and/or last item, or to use different templates for odd and even numbers. We can do this by specifying several templates, separated by a comma. In that case, cosmo will use the first template in the sequence, unless the table of values for the item contains a special field `_template`, in which case this field will be used as an index into the list of alternative templates. For instance, setting `_template` to 2 would tell cosmo to use the 2nd template for this item. > table.insert(mycards, {"2", "Clubs"}) > template = "You have: $do_cards[[$rank of $suit]],[[, $rank of $suit]],[[, and $rank of $suit]]" > = cosmo.f(template){ do_cards = function() for i,v in ipairs(mycards) do local t if i == #mycards then -- for the last item use the third template t = 3 elseif i~=1 then -- use the second template for items 2...n-1 t = 2 end cosmo.yield{rank=v[1], suit=v[2], _template=t} end end } You have: Ace of Spades, Queen of Diamonds, 10 of Heards, and 2 of Clubs Note that the first item is formatted without preceeding ", ", while the last item is preceeded by an extra "and". ## Deeper Nesting Templates and subtemplates can be nested to arbitrary depth. For instance, instead of formatting a set of cards, we can format a list of sets of cards: > players = {"John", "João"} > cards = {} > cards["John"] = mycards > cards["João"] = { {"Ace", "Diamonds"} } > template = "$do_players[[$player has $do_cards[[$rank of $suit]], [[, $rank of $suit]],[[, and $rank of $suit]]\n]]" > = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, do_cards = function() for i,v in ipairs(cards[p]) do local t if i == #mycards then t = 3 elseif i~=1 then -- use the second template for items 2...n-1 t = 2 end cosmo.yield{rank=v[1], suit=v[2], _template=t} end end } end end } John has Ace of Spades, Queen of Diamonds, 10 of Hearts, and 2 of Clubs João has Ace of Diamonds ## Scope Subtemplates can see values that were set in the higher scope: > template = "$do_players[[$do_cards[[$rank of $suit ($player), ]]]]" > = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, do_cards = function() for i,v in ipairs(cards[p]) do cosmo.yield{rank=v[1], suit=v[2]} end end, } end end } Ace of Spades (John), Queen of Diamonds (John), 10 of Hearts (John), 2 of Clubs (John), Ace of Diamonds (João), Note that in this case the field "player" is set in the table of values that is passed to `do_players`, but is used one level deeper - in `do_cards`. The scoping behavior can be overriden by setting a metatable on the environment you pass to the subtemplates. ## If Subtemplates and arguments let you implement a more generic conditional: > template = "$do_players[=[$player: $n card$if{ $plural }[[s]] $if{ $more, $n_more }[[(needs $2 more)]],[[(no more needed)]]\n]=]" > = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, n = #cards[p], ["if"] = function (arg) if arg[1] then arg._template = 1 else arg._template = 2 end cosmo.yield(arg) end, plural = #cards[p] > 1, more = #cards[p] < 3, n_more = 3 - #cards[p] } end end } John: 4 cards (no more needed) João: 1 card (needs 2 more) The conditional above is already present in Cosmo as `cosmo.cif`. Expressions in arguments make it more useful: > template = "$if{ math.fmod(x, 4) == 0, target = 'World' }[[ Hello $target! ]], [[ Hi $target! ]]" > result = cosmo.fill(template, { math = math, x = 2, ["if"] = cosmo.cif }) > assert(result == " Hi World! ") ## Other conditionals In some cases we want to format an set of values if some condition applies, and `cosmo.if` is not enough. This can be done with a function and a subtemplate by just replacing a for-loop with an if-block. However, since this is a common case, cosmo provides a function for it: > template = "$do_players[[$player: $n card$if_plural[[s]] $if_needs_more[[(needs $n more)]]\n]]" > = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, n = #cards[p], if_plural = cosmo.cond(#cards[p] > 1, {}), if_needs_more = cosmo.cond(#cards[p] < 3, { n = 3 - #cards[p] }) } end end } John: 4 cards João: 1 card (needs 2 more) Like `fill()`, `cond()` has a "shortcut" equivalent which takes only one parameter (the template) and returns a function: > = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, n = #cards[p], if_plural = cosmo.c(#cards[p] > 1){}, if_needs_more = cosmo.c(#cards[p] < 3){ n = 3-#cards[p] } } end end } John: 4 cards João: 1 card (needs 2 more) ## Map and Inject Cosmo provides two convenience functions for writing simple templates, `cosmo.map` and `cosmo.inject`. Both functions have to be passed in a template's environment. The `cosmo.map` function yields each of its arguments in sequence, and inject yields its whole argument table. A simple example: > template = "
    \n$map{ 'Spades', 'Hearts', 'Clubs', 'Diamonds'}[[
  1. $it
  2. \n]]
" > = cosmo.fill(template, { map = cosmo.map })
  1. Spades
  2. Hearts
  3. Clubs
  4. Diamonds
> template = "$inject{ suit = 'Spades' }[[Ace of $suit]]" > = cosmo.fill(template, { inject = cosmo.inject }) Ace of Spades ## Concat Putting a delimiter between each expansion of a subtemplate is so common that Cosmo provides also provides a convenience function for it, `cosmo.concat`. This is an example: > template = "$concat{ cards, ', ' }[[$1 of $2]]" > mycards = { {"Ace", "Spades"}, {"Queen", "Diamonds"}, {"10", "Hearts"} } > = cosmo.f(template){ cards = mycards, concat = cosmo.concat } Ace of Spades, Queen of Diamonds, 10 of Hearts API Reference ================================================= **cosmo.compile(*template*, *chunkname*)** - compiles *template* into a function that takes an environment and returns the filled template. Assigns *chunkname* as the name of this function **cosmo.fill(*template*, *env*)** - same as **cosmo.compile(*template*)(*env*)** **cosmo.yield(*env*, *is_literal*)** - fills the current subtemplate with *env* if *is_literal* is `nil` or `false` and adds it to the output stream; otherwise adds the the string *env* to the output stream **cosmo.cond(*bool*, *tab*)** - returns a function that yields an empty environment if *bool* is `nil` or `false` and *tab* otherwise **cosmo.c(*bool*)** - returns a function that takes a table *tab* and does the same thing as **cosmo.cond(*bool*, *tab*)** **cosmo.map{ ... }** - has to be used inside a template; yields each element of its argument in turn **cosmo.inject(env)** - has to be used inside a template; yields its argument **cosmo.cif{ *exp*, ... }** - has to be used inside a template; yields its argument to subtemplate 2 is *exp* is `nil` or `false` and to subtemplate 1 otherwise **cosmo.concat{ *list*, [*delim*] }** - has to be used inside a template; for each element of *list* yields it and, if it is not the last, yields the literal *delim* or ", " is *delim* is `nil` Contact Us ================================================= For more information please contact one of the authors, [Fabio Mascarenhas](mailto:mascarenhas_no_spam@acm.org) and [Yuri Takhteyev](http://takhteyev.org/contact/), or write to the [Sputnik Mailing List](http://sputnik.freewisdom.org/en/Mailing_List). Comments are welcome! License ================================================= Cosmo is free software: it can be used for both academic and commercial purposes at absolutely no cost. There are no royalties or GNU-like "copyleft" restrictions. Cosmo qualifies as Open Source software. Its licenses are compatible with GPL. The legal details are below. The spirit of the license is that you are free to use Cosmo for any purpose at no cost without having to ask us. The only requirement is that if you do use Cosmo, then you should give us credit by including the appropriate copyright notice somewhere in your product or its documentation. The original Cosmo library is designed and implemented by Yuri Takhteyev, with much feedback and inspiration by André Carregal. This version is a reimplementation by Fabio Mascarenhas, with aditional features. The implementations are not derived from licensed software. Copyright © 2008-2010 Fabio Mascarenhas. Copyright © 2007-2008 Yuri Takhteyev. --------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lua-cosmo-13.01.30/doc/cosmo.png000066400000000000000000000201261207723746400162460ustar00rootroot00000000000000PNG  IHDR^;sRGBbKGD pHYs  tIME)-^tEXtCommentCreated with The GIMPd%nIDATxil[gvhH+ddZlٔ#P4LbPmoP I L#}yLgJ臎h/vv*D7-l˖dҲ%⾼dZxK2% 133SXXj#1|nRpIHR0ǃrc>4,ܜ`CNNJKKiHL+C1Rǎu`p8055SZZJHL̠Czz:*@1T߁DFAII MbbbzpGEb"Xx^<}9&Ds0]<'1Q {ll}o: $ z^va6[xZ 0 `|~s*B 5 jkkwwjmFkkvwTzjQeJn[po`WYK흊46^Fo4ZZLjf"bp0IT]ųZiYHioA]%TZZ \+,҅ Z~)46^&1[,f::Lb"c7djjGo`VX^ ^KVĴIMM]7y>~ 9&FcBLzuƂDBVV&&&@\?llBW>`17ǿn:|X .9Z[x>VMMHL1Ṙq2]?3-`Gcfy1&d2b-->R_Q i;cBk4,o|_Aitt/-buf qD…Qܽy@DV UUۏG-U VjSpc׵(x|!> z3 zHOOL&~Dٌ/| {Z-Cq uˉX켈m_QX+Wf#JVߪSBLa8 PXX(::?Q ԩ4Ho,fOFj q iK=1TT䢢"'f1mMܒz܆111ϟYV=!UG'&|1|a&JKQXkZtv/ixxx jjJZW 0p"A L< *OƪFcRn,>|#ޛУ.ܽ+ppDft$f Z[I1 64zqU,//3ǝ8qeeeq}EBzRS%"I[#O?BbDHxv;|>RRRoSS~l3Z,O(\,Ӌ/w}7ϊW<߾D(Ȑ6u1].nݺٌ!aqqsssfEяP*-^.B&h4BP9V}Gk_ d9y2 | :Aj"|X?ď~5wILKKK~j;8A1r]x],͆QaGv0$qȑ1V{BڦтZfX](`TcU* M!+ĴgϞ1ǔ!%%j w0+NxL{$mSURT(,gM /|@_EV 劭%_Dw 1ʼn|r@?41#<@OfC [ "x\U'499 ôJ|V4ݻ+XZ 0fuunΊzdTL` ;jZ63; IQU^gp0T^Op8_d2zq*&UZḚ`ngtii)!ןLsIbz_8 Z1br<nj9Z-ٰދ50QbӲ]/&'gQQў}0>cz ݯ>Hm+8њ*힤|>~"/O{DS 'fu:cjnɵk34Pn.ӨiN̽x>M KR JrɚeW,(JU]] G#V;.jΓPҰFJ jV^992ރR44<;1'sNٵk? 2M[VJ%nٌ.Wdң~u?.0ӳB0\RR"fV ?y뽮)Ytvv"55z )tCn^\ 1/&\@Rf}^\ NX^wl*2pၷW#Ӊ\~=%LX)){O1)P8  c~>Ǐ_>tرT^]R _WVM TVEiܼyO~ܾ]d([ VK"~ j| wobIB0^]7EKqV~}Yt1{̙3kAl6nC&A!## bpI#dpRS%cNN\E͕*~633~8!zr9?9aϝav֟t||}N'0>>l$锔梲ِHy#iR8w.#*!m^Wy8~< V: =5)š.s=l6t;_!Gχ \~cccoOMyR)P_Cyr9 I1Ӣ|NESR-b O= uKa~ky[i?3h8*//YYY +L%8}4;h4\,ZL,@T^uofgdnN;e4b͕3XwZ7*8 V7=m[VV\Xe&ˑht:)}X<[К\o틋BɓkoH.GMDDFLɉw2l9czs>P?*OP&^jE5z}AZ|{ EUβbpםc}k#>D&oX~4K~CmD/eU/2UU*ߴ#g[C ۷S>_^^$jh׋n%i2 p] -p8{6gϲy:)} o]=i.% ƒcx[H{NLu9FczݦY av6`vݼ< 1Bܽ+Z #z 43sxxCCĊCfffT!oݺ NJR>|711v/10f.^vItH!`ol de0?Gg+sȢ Qp8^A8p7 xce`qq1awe\vD_WqD0ƍuIhMVQy}SOg7lVF#ؼ; f Ϛ) }zEZRRRPUU}-UYY{.T1SS~sJW;geɠPH^M!|̌bEf}W %?u*yhR%! |> 2wT*))Aff&155uH\&ĉt{?h4ܬp8>t:dgguc47* ~LNO`|9qZUbZѣGP(0001§ho߾/33gΜf(&&&r" U*"++ Gޓb>}>qܹjNHq l 0[ZL1cY/rb``dcIR!//ǎ\.B8{VhUbzP4__ X⋀LmY͂ͅd2\.Ri7\.Cٳ5T*jjj>|wgSR| 5sq˼Ջ/al ? ?1/ltx{ӑ[ k== ~?,`* MMdE$J%ÇU 6j!WZ-##MMvq(++[ZL;A~"1:ꋪIRW!IcIL^Dcǎ1]tQ>뫯#6 U{D;VW_ՓRPyuuuĨR=-zmmwQbI"8y$233!H Hjq fUX/qARR8:!GX\^CgE}ITL&=,hAI U qS)4D,I8--&X,DIk5ܿx 5X>p 'C=jG{{/{yG u-kGW P~ib{f_N"f9oYƿLחiYANB[g/-<U[dh,D}}9Y!gvvzVz]MEDm[{P(Ytk \$GFS3LNN v>}zO&HL  FFF0::ʞlF1>RDB"$N8'O``W'2f$$Ƙc4 jjj 1ݻw]JJ jkkP(hHLD$q A 4a$&%$0xff&hHLD$\.n޼ 'JQSSCG+HL]ϧI#1z~zTB***Bee%EHLfnܸ!x P(>f5Z-Μ9#ͫ҉8Ng"==&Dlۂut:Ν;G#"100eA׎D<{ O>eIMM%!$&sӽH$JF"rp-u`@^^MAb 8ܹsZFUUm$&ǙR);44gFFFc8hDII MgzE( sLEEV+<d2rrr`4ji=D7p8^I@&gAb"Z3 HLAD$& HLAb"6s_9_>IENDB`lua-cosmo-13.01.30/doc/dummy000066400000000000000000000000001207723746400154630ustar00rootroot00000000000000lua-cosmo-13.01.30/doc/index.html000066400000000000000000000457641207723746400164340ustar00rootroot00000000000000

Cosmo

Overview

Cosmo is a “safe templates” engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates.

Installation

The current version of Cosmo is 13.01.30. This release adds Lua 5.2 support.

The previous version, 10.04.06, added, expressions to selectors $(<exp>), allowed nested [[ ]] in templates, made commas between subtemplates optional, and added a second parameter to cosmo.yield that tells Cosmo the first parameter is a literal to be included in the expansion instead of an environment.

Cosmo is installed as a rock. To install the most recent release do luarocks install cosmo. The Cosmo rock is in the standard repository. Installation on UNIX-based systems need the gcc toolchain.

Using Cosmo

Simple Form Filling

Let’s start with a simple example of filling a set of scalar values into a template: Here are a few examples of Cosmo in use:

> values = { rank="Ace", suit="Spades" } 
> template = "$rank of $suit"
> require("cosmo")
> = cosmo.fill(template, values)
Ace of Spades

Note that the template is a string that marks where values should go. We call a template variable like $rank a selector, and rank is the selector’s name. The table passed to cosmo.fill is the environment, and it provides the values. $rank will get replaced by value.rank (“Ace”) and $suit will get replaced by value.suit (“Spades”).

cosmo.fill takes two parameters at once. Cosmo also provides a “shortcut” method f() which takes only one parameter - the template - and returns a function that then takes the second parameter. This allows for a more compact notation:

> = cosmo.f(template){ rank="Ace", suit="Spades" } 
Ace of Spades

A selector can be either a string or a Lua expression in parenthesis, like $("foo" .. "bar") is replaced by foobar in the template. Any variables in the expression are looked-up in the current template environment, so $(foo) is the same as $foo, and $(rank .. suit) would be replaced by AceSpades in the previous example.

Nested Values

You aren’t restricted to scalar values; your values can be Lua tables that you can destructure using a $val|key1|key2|…|keyn syntax. For example:

> values = { cards = { { rank = "Ace" , suit = "Spades" } } }
> template = "$cards|1|rank of $cards|1|suit"
> = cosmo.fill(template, values)
Ace of Spades

As you can see above, you can either use numbers or strings as keys.

Arguments

You can also pass arguments to a selector using the syntax $selector{ args }. The syntax for the argument list is the same as a Lua table constructor, but function definitions are not allowed, and you can use template selectors, which are looked up in the template environment.

If you pass an argument list and the selector maps to a function then Cosmo calls this function with the argument list as a table, and the selector expands to what the function returns. For example:

> values = { message = function (arg) return arg.rank .. " of "
     .. arg.suit end }
> template = "$message{ rank = 'Ace', suit = 'Spades' }"
> = cosmo.fill(template, values)
Ace of Spades

Subtemplates

Now, suppose we have not just one card, but several. Cosmo allows us to handle this case with “subtemplates”

> mycards = { {rank="Ace", suit="Spades"}, {rank="Queen", suit="Diamonds"}, {rank="10", suit="Hearts"} } 
> template = "$do_cards[[$rank of $suit, ]]"
> = cosmo.fill(template, {do_cards = mycards})  
Ace of Spades, Queen of Diamonds, 10 of Hearts,

The subtemplate “$rank or $suit” could be enclosed in [[...]], [=[...]=], [==[...]==], etc. - just like Lua’s long-quoted strings. Again, we can use the shortcut f():

> = cosmo.f(template){do_cards = mycards}  
Ace of Spades, Queen of Diamonds, 10 of Hearts,

Subtemplates with Functions

If we don’t have a ready table that would match the template, we can set the value of do_cards to a function, which will yield a set of values for the subtemplate each time it’s called:

> mycards = { {"Ace", "Spades"}, {"Queen", "Diamonds"}, {"10", "Hearts"} }
> = cosmo.f(template){
       do_cards = function()
          for i,v in ipairs(mycards) do
             cosmo.yield{rank=v[1], suit=v[2]}
          end
       end
    }
Ace of Spades, Queen of Diamonds, 10 of Hearts,

You can also pass a list of arguments to this function:

> template = "$do_cards{ true, false, true }[[$rank of $suit, ]]"
> mycards = { {"Ace", "Spades"}, {"Queen", "Diamonds"}, {"10", "Hearts"} }
> = cosmo.f(template){
       do_cards = function(arg)
          for i,v in ipairs(mycards) do
             if arg[i] then cosmo.yield{rank=v[1], suit=v[2]} end
          end
       end
    }
Ace of Spades, 10 of Hearts,

Finally, you can pass a literal to be included in the expansion instead of an environment. An example:

> template = "$do_cards{ true, false, true }[[$rank of $suit]]"
> mycards = { {"Ace", "Spades"}, {"Queen", "Diamonds"}, {"10", "Hearts"} }
> = cosmo.f(template){
       do_cards = function(arg)
          local n = #mycards
          for i,v in ipairs(mycards) do
             cosmo.yield{rank=v[1], suit=v[2]}
             if i < n then cosmo.yield(", ", true) end
          end
       end
    }
Ace of Spades, Queen of Diamonds, 10 of Hearts

Alternative Subtemplates

In some cases we may want to use differente templates for different items in the list. For example, we might want to use a different template for the first and/or last item, or to use different templates for odd and even numbers. We can do this by specifying several templates, separated by a comma. In that case, cosmo will use the first template in the sequence, unless the table of values for the item contains a special field _template, in which case this field will be used as an index into the list of alternative templates. For instance, setting _template to 2 would tell cosmo to use the 2nd template for this item.

> table.insert(mycards, {"2", "Clubs"})
> template = "You have: $do_cards[[$rank of $suit]],[[, $rank of $suit]],[[, and $rank of $suit]]"
> = cosmo.f(template){
       do_cards = function()
          for i,v in ipairs(mycards) do
             local t
             if i == #mycards then -- for the last item use the third template
                t = 3
             elseif i~=1 then -- use the second template for items 2...n-1
                t = 2
             end
             cosmo.yield{rank=v[1], suit=v[2], _template=t}
          end
       end
    }

You have: Ace of Spades, Queen of Diamonds, 10 of Heards, and 2 of Clubs

Note that the first item is formatted without preceeding “, ”, while the last item is preceeded by an extra “and”.

Deeper Nesting

Templates and subtemplates can be nested to arbitrary depth. For instance, instead of formatting a set of cards, we can format a list of sets of cards:

> players = {"John", "João"}
> cards = {}
> cards["John"] = mycards
> cards["João"] = { {"Ace", "Diamonds"} }
> template = "$do_players[[$player has $do_cards[[$rank of $suit]],
    [[, $rank of $suit]],[[, and $rank of $suit]]\n]]"
> = cosmo.f(template){
       do_players = function()
          for i,p in ipairs(players) do
             cosmo.yield {
                player = p,
                do_cards = function()
                   for i,v in ipairs(cards[p]) do
                      local t
                      if i == #mycards then
                         t = 3
                      elseif i~=1 then -- use the second template for items 2...n-1
                         t = 2
                      end
                      cosmo.yield{rank=v[1], suit=v[2], _template=t}
                   end
                end
             }         
         end
      end
    }

John has Ace of Spades, Queen of Diamonds, 10 of Hearts, and 2 of Clubs
João has Ace of Diamonds

Scope

Subtemplates can see values that were set in the higher scope:

> template = "$do_players[[$do_cards[[$rank of $suit ($player), ]]]]"
> = cosmo.f(template){
       do_players = function()
          for i,p in ipairs(players) do
             cosmo.yield {
                player = p,
                do_cards = function()
                   for i,v in ipairs(cards[p]) do
                      cosmo.yield{rank=v[1], suit=v[2]}
                   end
                end,
             }         
          end
       end
    }

Ace of Spades (John), Queen of Diamonds (John), 10 of Hearts (John), 2 of Clubs (John), Ace of Diamonds (João), 

Note that in this case the field “player” is set in the table of values that is passed to do_players, but is used one level deeper - in do_cards.

The scoping behavior can be overriden by setting a metatable on the environment you pass to the subtemplates.

If

Subtemplates and arguments let you implement a more generic conditional:

> template = "$do_players[=[$player: $n card$if{ $plural }[[s]]
                   $if{ $more, $n_more }[[(needs $2 more)]],[[(no more needed)]]\n]=]"
> = cosmo.f(template){
       do_players = function()
          for i,p in ipairs(players) do
             cosmo.yield {
                player = p,
                n = #cards[p],
                ["if"] = function (arg)
                   if arg[1] then arg._template = 1 else arg._template = 2 end
                   cosmo.yield(arg)
                         end,
                plural = #cards[p] > 1,
                more = #cards[p] < 3,
                n_more = 3 - #cards[p]
             }         
          end
       end
    }

John: 4 cards (no more needed)
João: 1 card (needs 2 more)   

The conditional above is already present in Cosmo as cosmo.cif. Expressions in arguments make it more useful:

> template = "$if{ math.fmod(x, 4) == 0, target = 'World' }[[ Hello $target! ]],
   [[ Hi $target! ]]"
> result = cosmo.fill(template, { math = math, x = 2, ["if"] = cosmo.cif })
> assert(result == " Hi World! ")

Other conditionals

In some cases we want to format an set of values if some condition applies, and cosmo.if is not enough. This can be done with a function and a subtemplate by just replacing a for-loop with an if-block. However, since this is a common case, cosmo provides a function for it:

> template = "$do_players[[$player: $n card$if_plural[[s]] $if_needs_more[[(needs $n more)]]\n]]"
> = cosmo.f(template){
       do_players = function()
          for i,p in ipairs(players) do
             cosmo.yield {
                player = p,
                n = #cards[p],
                if_plural = cosmo.cond(#cards[p] > 1, {}),
                if_needs_more = cosmo.cond(#cards[p] < 3, { n = 3 - #cards[p] })
             }         
          end
       end
    }

John: 4 cards
João: 1 card (needs 2 more)

Like fill(), cond() has a “shortcut” equivalent which takes only one parameter (the template) and returns a function:

> = cosmo.f(template){
       do_players = function()
          for i,p in ipairs(players) do
             cosmo.yield {
                player = p,
                n = #cards[p],
                if_plural = cosmo.c(#cards[p] > 1){},
                if_needs_more = cosmo.c(#cards[p] < 3){ n = 3-#cards[p] }
             }         
          end
       end
    }

John: 4 cards
João: 1 card (needs 2 more)

Map and Inject

Cosmo provides two convenience functions for writing simple templates, cosmo.map and cosmo.inject. Both functions have to be passed in a template’s environment. The cosmo.map function yields each of its arguments in sequence, and inject yields its whole argument table. A simple example:

> template = "<ol>\n$map{ 'Spades', 'Hearts', 'Clubs', 'Diamonds'}[[<li>$it</li>\n]]</ol>"
> = cosmo.fill(template, { map = cosmo.map })
<ol>
<li>Spades</li>
<li>Hearts</li>
<li>Clubs</li>
<li>Diamonds</li>
</ol>
> template = "$inject{ suit = 'Spades' }[[Ace of <b>$suit</b>]]"
> = cosmo.fill(template, { inject = cosmo.inject })
Ace of <b>Spades</b>

Concat

Putting a delimiter between each expansion of a subtemplate is so common that Cosmo provides also provides a convenience function for it, cosmo.concat. This is an example:

> template = "$concat{ cards, ', ' }[[$1 of $2]]"
> mycards = { {"Ace", "Spades"}, {"Queen", "Diamonds"}, {"10", "Hearts"} }
> = cosmo.f(template){
       cards = mycards,
       concat = cosmo.concat
   }
Ace of Spades, Queen of Diamonds, 10 of Hearts

API Reference

cosmo.compile(template, chunkname) - compiles template into a function that takes an environment and returns the filled template. Assigns chunkname as the name of this function

cosmo.fill(template, env) - same as cosmo.compile(template)(env)

cosmo.yield(env, is_literal) - fills the current subtemplate with env if is_literal is nil or false and adds it to the output stream; otherwise adds the the string env to the output stream

cosmo.cond(bool, tab) - returns a function that yields an empty environment if bool is nil or false and tab otherwise

cosmo.c(bool) - returns a function that takes a table tab and does the same thing as cosmo.cond(bool, tab)

cosmo.map{ … } - has to be used inside a template; yields each element of its argument in turn

cosmo.inject(env) - has to be used inside a template; yields its argument

cosmo.cif{ exp, … } - has to be used inside a template; yields its argument to subtemplate 2 is exp is nil or false and to subtemplate 1 otherwise

cosmo.concat{ list, [delim] } - has to be used inside a template; for each element of list yields it and, if it is not the last, yields the literal delim or “, ” is delim is nil

Contact Us

For more information please contact one of the authors, Fabio Mascarenhas and Yuri Takhteyev, or write to the Sputnik Mailing List.

Comments are welcome!

License

Cosmo is free software: it can be used for both academic and commercial purposes at absolutely no cost. There are no royalties or GNU-like “copyleft” restrictions. Cosmo qualifies as Open Source software. Its licenses are compatible with GPL. The legal details are below.

The spirit of the license is that you are free to use Cosmo for any purpose at no cost without having to ask us. The only requirement is that if you do use Cosmo, then you should give us credit by including the appropriate copyright notice somewhere in your product or its documentation.

The original Cosmo library is designed and implemented by Yuri Takhteyev, with much feedback and inspiration by André Carregal. This version is a reimplementation by Fabio Mascarenhas, with aditional features. The implementations are not derived from licensed software.

Copyright © 2008-2010 Fabio Mascarenhas. Copyright © 2007-2008 Yuri Takhteyev.


Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

lua-cosmo-13.01.30/rockspec/000077500000000000000000000000001207723746400154635ustar00rootroot00000000000000lua-cosmo-13.01.30/rockspec/cosmo-10.03.31-1.rockspec000066400000000000000000000013741207723746400213620ustar00rootroot00000000000000package = "Cosmo" version = "10.03.31-1" description = { summary = "Safe templates for Lua", detailed = [[ Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. ]], license = "MIT/X11", homepage = "http://cosmo.luaforge.net" } dependencies = { "lpeg >= 0.9" } source = { url = "http://github.com/downloads/mascarenhas/cosmo/cosmo-10.03.31.tar.gz" } build = { type = "builtin", modules = { cosmo = "src/cosmo.lua", ["cosmo.fill"] = "src/cosmo/fill.lua", ["cosmo.grammar"] = "src/cosmo/grammar.lua", }, copy_directories = { "doc", "samples", "tests" } } lua-cosmo-13.01.30/rockspec/cosmo-10.04.06-1.rockspec000066400000000000000000000013741207723746400213650ustar00rootroot00000000000000package = "Cosmo" version = "10.04.06-1" description = { summary = "Safe templates for Lua", detailed = [[ Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. ]], license = "MIT/X11", homepage = "http://cosmo.luaforge.net" } dependencies = { "lpeg >= 0.9" } source = { url = "http://github.com/downloads/mascarenhas/cosmo/cosmo-10.04.06.tar.gz" } build = { type = "builtin", modules = { cosmo = "src/cosmo.lua", ["cosmo.fill"] = "src/cosmo/fill.lua", ["cosmo.grammar"] = "src/cosmo/grammar.lua", }, copy_directories = { "doc", "samples", "tests" } } lua-cosmo-13.01.30/rockspec/cosmo-13.01.30-1.rockspec000066400000000000000000000013611207723746400213560ustar00rootroot00000000000000package = "Cosmo" version = "13.01.30-1" description = { summary = "Safe templates for Lua", detailed = [[ Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. ]], license = "MIT/X11", homepage = "http://cosmo.luaforge.net" } dependencies = { "lpeg >= 0.9" } source = { url = "http://www.keplerproject.org/files/cosmo-13.01.30.tar.gz" } build = { type = "builtin", modules = { cosmo = "src/cosmo.lua", ["cosmo.fill"] = "src/cosmo/fill.lua", ["cosmo.grammar"] = "src/cosmo/grammar.lua", }, copy_directories = { "doc", "samples", "tests" } } lua-cosmo-13.01.30/rockspec/cosmo-8.02.18-1.rockspec000066400000000000000000000026011207723746400213070ustar00rootroot00000000000000package = "Cosmo" version = "8.02.18-1" description = { summary = "Safe templates for Lua", detailed = [[ Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. ]], license = "MIT/X11", homepage = "http://cosmo.luaforge.net" } dependencies = { } source = { url = "http://cosmo.luaforge.net/cosmo-8.02.18.tar.gz" } build = { platforms = { unix = { type = "make", build_pass = true, build_target = "all", install_target = "install-rocks", build_variables = { LIB_OPTION = "$(LIBFLAG)", CFLAGS = "$(CFLAGS) -I$(LUA_INCDIR)", }, install_variables = { PREFIX = "$(PREFIX)", LUA_BIN = "/usr/bin/env lua", LUA_DIR= "$(LUADIR)", LUA_LIBDIR = "$(LIBDIR)" } }, win32 = { type = "make", build_pass = true, build_target = "all", install_target = "install-rocks", build_variables = { LIB_OPTION = "$(LUA_LIBDIR)\\lua5.1.lib", CFLAGS = "$(CFLAGS)", LUA_INCLUDE = "$(LUA_INCDIR)" }, install_variables = { PREFIX = "$(PREFIX)", LUA_BIN = "/usr/bin/env lua", LUA_DIR= "$(LUADIR)", LUA_LIBDIR = "$(LIBDIR)" } } } } lua-cosmo-13.01.30/rockspec/cosmo-8.04.04-1.rockspec000066400000000000000000000026211207723746400213060ustar00rootroot00000000000000package = "Cosmo" version = "8.04.04-1" description = { summary = "Safe templates for Lua", detailed = [[ Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. ]], license = "MIT/X11", homepage = "http://cosmo.luaforge.net" } dependencies = { "lpeg >= 0.8.1" } source = { url = "http://cosmo.luaforge.net/cosmo-8.04.04.tar.gz" } build = { platforms = { unix = { type = "make", build_pass = true, build_target = "all", install_target = "install-rocks", build_variables = { LIB_OPTION = "$(LIBFLAG)", CFLAGS = "$(CFLAGS) -I$(LUA_INCDIR)", }, install_variables = { PREFIX = "$(PREFIX)", LUA_BIN = "/usr/bin/env lua", LUA_DIR= "$(LUADIR)", LUA_LIBDIR = "$(LIBDIR)" } }, win32 = { type = "make", build_pass = true, build_target = "all", install_target = "install-rocks", build_variables = { LIB_OPTION = "$(LUA_LIBDIR)\\lua5.1.lib", CFLAGS = "$(CFLAGS)", LUA_INCLUDE = "$(LUA_INCDIR)" }, install_variables = { PREFIX = "$(PREFIX)", LUA_BIN = "/usr/bin/env lua", LUA_DIR= "$(LUADIR)", LUA_LIBDIR = "$(LIBDIR)" } } } } lua-cosmo-13.01.30/rockspec/cosmo-8.04.14-1.rockspec000066400000000000000000000026211207723746400213070ustar00rootroot00000000000000package = "Cosmo" version = "8.04.14-1" description = { summary = "Safe templates for Lua", detailed = [[ Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. ]], license = "MIT/X11", homepage = "http://cosmo.luaforge.net" } dependencies = { "lpeg >= 0.8.1" } source = { url = "http://cosmo.luaforge.net/cosmo-8.04.14.tar.gz" } build = { platforms = { unix = { type = "make", build_pass = true, build_target = "all", install_target = "install-rocks", build_variables = { LIB_OPTION = "$(LIBFLAG)", CFLAGS = "$(CFLAGS) -I$(LUA_INCDIR)", }, install_variables = { PREFIX = "$(PREFIX)", LUA_BIN = "/usr/bin/env lua", LUA_DIR= "$(LUADIR)", LUA_LIBDIR = "$(LIBDIR)" } }, win32 = { type = "make", build_pass = true, build_target = "all", install_target = "install-rocks", build_variables = { LIB_OPTION = "$(LUA_LIBDIR)\\lua5.1.lib", CFLAGS = "$(CFLAGS)", LUA_INCLUDE = "$(LUA_INCDIR)" }, install_variables = { PREFIX = "$(PREFIX)", LUA_BIN = "/usr/bin/env lua", LUA_DIR= "$(LUADIR)", LUA_LIBDIR = "$(LIBDIR)" } } } } lua-cosmo-13.01.30/rockspec/cosmo-8.04.14-2.rockspec000066400000000000000000000013471207723746400213140ustar00rootroot00000000000000package = "Cosmo" version = "8.04.14-2" description = { summary = "Safe templates for Lua", detailed = [[ Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. ]], license = "MIT/X11", homepage = "http://cosmo.luaforge.net" } dependencies = { "lpeg >= 0.8.1" } source = { url = "http://cosmo.luaforge.net/cosmo-8.04.14.tar.gz" } build = { type = "module", modules = { cosmo = "src/cosmo.lua", ["cosmo.fill"] = "src/cosmo/fill.lua", ["cosmo.grammar"] = "src/cosmo/grammar.lua", }, copy_directories = { "doc", "samples", "tests" } } lua-cosmo-13.01.30/rockspec/cosmo-9.09.22-1.rockspec000066400000000000000000000013451207723746400213160ustar00rootroot00000000000000package = "Cosmo" version = "9.09.22-1" description = { summary = "Safe templates for Lua", detailed = [[ Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. ]], license = "MIT/X11", homepage = "http://cosmo.luaforge.net" } dependencies = { "lpeg >= 0.9" } source = { url = "http://cosmo.luaforge.net/cosmo-9.09.22.tar.gz" } build = { type = "module", modules = { cosmo = "src/cosmo.lua", ["cosmo.fill"] = "src/cosmo/fill.lua", ["cosmo.grammar"] = "src/cosmo/grammar.lua", }, copy_directories = { "doc", "samples", "tests" } } lua-cosmo-13.01.30/rockspec/cosmo-current-1.rockspec000066400000000000000000000013371207723746400221600ustar00rootroot00000000000000package = "Cosmo" version = "current-1" description = { summary = "Safe templates for Lua", detailed = [[ Cosmo is a "safe templates" engine. It allows you to fill nested templates, providing many of the advantages of Turing-complete template engines, without without the downside of allowing arbitrary code in the templates. ]], license = "MIT/X11", homepage = "http://cosmo.luaforge.net" } dependencies = { "lpeg >= 0.8.1" } source = { url = "git://github.com/mascarenhas/cosmo.git" } build = { type = "module", modules = { cosmo = "src/cosmo.lua", ["cosmo.fill"] = "src/cosmo/fill.lua", ["cosmo.grammar"] = "src/cosmo/grammar.lua", }, copy_directories = { "doc", "samples", "tests" } } lua-cosmo-13.01.30/samples/000077500000000000000000000000001207723746400153165ustar00rootroot00000000000000lua-cosmo-13.01.30/samples/sample.lua000066400000000000000000000034401207723746400173030ustar00rootroot00000000000000local cosmo = require "cosmo" template = [==[

$list_name

    $do_items[=[
  • $item
  • ]=]
]==] print(cosmo.fill(template, { list_name = "My List", do_items = function() for i=1,5 do cosmo.yield { item = i } end end } )) print(cosmo.fill(template, { list_name = "My List", do_items = function() for i=1,5 do cosmo.yield { item = i } end end } )) warn_about_alligators = true print(cosmo.fill ( "-- $if_warning[=[Beware of $warning!]=] --", { if_warning = cosmo.cond(warn_about_alligators, { warning = "ALLIGATORS" } ) } )) warn_about_alligators = false print(cosmo.fill ( "-- $if_warning[=[Beware of $warning!]=] --", { if_warning = cosmo.cond(warn_about_alligators, { warning = "ALLIGATORS" } ) } )) template = [==[

$list_name

    $do_items{ $foo }[=[
  • $item
  • ]=]
]==] print(cosmo.fill(template, { list_name = "My List", foo = "Hello ", do_items = function(args) for i=1,5 do cosmo.yield { item = args[1] .. i } end end } )) print(cosmo.fill(template, { list_name = "My List", foo = "Hello ", do_items = function(args) for i=1,5 do cosmo.yield { item = args[1] .. i } end end } )) lua-cosmo-13.01.30/src/000077500000000000000000000000001207723746400144415ustar00rootroot00000000000000lua-cosmo-13.01.30/src/cosmo.lua000066400000000000000000000236641207723746400162770ustar00rootroot00000000000000local require = require local grammar = require "cosmo.grammar" local interpreter = require "cosmo.fill" local loadstring = loadstring if _VERSION == "Lua 5.2" then _ENV = setmetatable({}, { __index = _G }) else module(..., package.seeall) _ENV = _M end yield = coroutine.yield local preamble = [[ local is_callable, insert, concat, setmetatable, getmetatable, type, wrap, tostring, check_selector = ... local function unparse_name(parsed_selector) local name = parsed_selector:match("^env%%['([%%w_]+)'%%]$") if name then name = "$" .. name end return name or parsed_selector end local function prepare_env(env, parent) local __index = function (t, k) local v = env[k] if not v then v = parent[k] end return v end local __newindex = function (t, k, v) env[k] = v end return setmetatable({ self = env }, { __index = __index, __newindex = __newindex }) end local id = function () end local template_func = %s return function (env, opts) opts = opts or {} local out = opts.out or {} template_func(out, env, opts) return concat(out, opts.delim) end ]] local compiled_template = [[ function (out, env, opts) if type(env) == "string" then env = { it = env } end $parts[=[ insert(out, $quoted_text) ]=], [=[ local selector_name = unparse_name($selector) local selector = $parsed_selector $if_subtemplate[==[ local subtemplates = {} $subtemplates[===[ subtemplates[$i] = $subtemplate ]===] local default = id if opts.fallback then default = subtemplates[1] end $if_args[===[ check_selector(selector_name, selector) for e, literal in wrap(selector), $args, true do if literal then insert(out, tostring(e)) else if type(e) ~= "table" then e = prepare_env({ it = tostring(e) }, env) else e = prepare_env(e, env) end (subtemplates[e.self._template or 1] or default)(out, e, opts) end end ]===], [===[ if type(selector) == 'table' then for _, e in ipairs(selector) do if type(e) ~= "table" then e = prepare_env({ it = tostring(e) }, env) else e = prepare_env(e, env) end (subtemplates[e.self._template or 1] or default)(out, e, opts) end else check_selector(selector_name, selector) for e, literal in wrap(selector), nil, true do if literal then insert(out, tostring(e)) else if type(e) ~= "table" then e = prepare_env({ it = tostring(e) }, env) else e = prepare_env(e, env) end (subtemplates[e.self._template or 1] or default)(out, e, opts) end end end ]===] ]==], [==[ $if_args[===[ check_selector(selector_name, selector) selector = selector($args, false) insert(out, tostring(selector)) ]===], [===[ if is_callable(selector) then insert(out, tostring(selector())) else if not selector and opts.passthrough then selector = selector_name end insert(out, tostring(selector or "")) end ]===] ]==] ]=] end ]] local function is_callable(f) if type(f) == "function" then return true end local meta = getmetatable(f) if meta and meta.__call then return true end return false end local function check_selector(name, selector) if not is_callable(selector) then error("selector " .. name .. " is not callable but is " .. type(selector)) end end local function compile_template(chunkname, template_code) local template_func, err = loadstring(string.format(preamble, template_code), chunkname) if not template_func then error("syntax error when compiling template: " .. err) else return template_func(is_callable, table.insert, table.concat, setmetatable, getmetatable, type, coroutine.wrap, tostring, check_selector) end end local compiler = {} function compiler.template(template) assert(template.tag == "template") local parts = {} for _, part in ipairs(template.parts) do parts[#parts+1] = compiler[part.tag](part) end return interpreter.fill(compiled_template, { parts = parts }) end function compiler.text(text) assert(text.tag == "text") return { _template = 1, quoted_text = string.format("%q", text.text) } end function compiler.appl(appl) assert(appl.tag == "appl") local selector, args, subtemplates = appl.selector, appl.args, appl.subtemplates local ta = { _template = 2, selector = string.format("%q", selector), parsed_selector = selector } local do_subtemplates = function () for i, subtemplate in ipairs(subtemplates) do yield{ i = i, subtemplate = compiler.template(subtemplate) } end end if #subtemplates == 0 then if args and args ~= "" and args ~= "{}" then ta.if_subtemplate = { { _template = 2, if_args = { { _template = 1, args = args } } } } else ta.if_subtemplate = { { _template = 2, if_args = { { _template = 2 } } } } end else if args and args ~= "" and args ~= "{}" then ta.if_subtemplate = { { _template = 1, subtemplates = do_subtemplates, if_args = { { _template = 1, args = args } } } } else ta.if_subtemplate = { { _template = 1, subtemplates = do_subtemplates, if_args = { { _template = 2 } } } } end end return ta end local cache = {} setmetatable(cache, { __index = function (tab, key) local new = {} tab[key] = new return new end, __mode = "v" }) function compile(template, chunkname, opts) opts = opts or {} template = template or "" chunkname = chunkname or template local compiled_template = cache[template][chunkname] grammar.ast = opts.parser or grammar.default if not compiled_template then compiled_template = compile_template(chunkname, compiler.template(grammar.ast:match(template))) cache[template][chunkname] = compiled_template end return compiled_template end local filled_templates = {} setmetatable(filled_templates, { __mode = "k" }) function fill(template, env, opts) opts = opts or {} template = template or "" local start = template:match("^(%[=*%[)") if start then template = template:sub(#start + 1, #template - #start) end if filled_templates[template] then return compile(template, opts.chunkname, opts.parser)(env, opts) else filled_templates[template] = true return interpreter.fill(template, env, opts) end end local nop = function () end function cond(bool, table) if bool then return function () yield(table) end else return nop end end f = compile function c(bool) if bool then return function (table) return function () yield(table) end end else return function (table) return nop end end end function map(arg, has_block) if has_block then for _, item in ipairs(arg) do yield(item) end else return table.concat(arg) end end function inject(arg) yield(arg) end function cif(arg, has_block) if not has_block then error("this selector needs a block") end if arg[1] then arg._template = 1 else arg._template = 2 end yield(arg) end function concat(arg) local list, sep = arg[1], arg[2] or ", " local size = #list for i, e in ipairs(list) do if type(e) == "table" then if i ~= size then yield(e) yield(sep, true) else yield(e) end else if i ~= size then yield{ it = e } yield(sep, true) else yield{ it = e } end end end end function make_concat(list) return function (arg) local sep = (arg and arg[1]) or ", " local size = #list for i, e in ipairs(list) do if type(e) == "table" then if i ~= size then yield(e) yield(sep, true) else yield(e) end else if i ~= size then yield{ it = e } yield(sep, true) else yield{ it = e } end end end end end function cfor(args) local name, list, args = args[1], args[2], args[3] if type(list) == "table" then for i, item in ipairs(list) do yield({ [name] = item, i = i }) end else for item, literal in coroutine.wrap(list), args, true do if literal then yield(item, true) else yield({ [name] = item }) end end end end return _ENV lua-cosmo-13.01.30/src/cosmo/000077500000000000000000000000001207723746400155615ustar00rootroot00000000000000lua-cosmo-13.01.30/src/cosmo/fill.lua000066400000000000000000000103131207723746400172100ustar00rootroot00000000000000 local grammar = require "cosmo.grammar" if _VERSION == "Lua 5.2" then _ENV = setmetatable({}, { __index = _G }) else module(..., package.seeall) _ENV = _M end local function is_callable(f) if type(f) == "function" then return true end local meta = getmetatable(f) if meta and meta.__call then return true end return false end local insert = table.insert local concat = table.concat local function prepare_env(env, parent) local __index = function (t, k) local v = env[k] if not v then v = parent[k] end return v end local __newindex = function (t, k, v) env[k] = v end return setmetatable({ self = env }, { __index = __index, __newindex = __newindex }) end local interpreter = {} function interpreter.text(state, text) assert(text.tag == "text") insert(state.out, text.text) end local function check_selector(name, selector) if not is_callable(selector) then error("selector " .. name .. " is not callable but is " .. type(selector)) end end local function unparse_name(parsed_selector) local name = parsed_selector:match("^env%['([%w_]+)'%]$") if name then name = "$" .. name end return name or parsed_selector end function interpreter.appl(state, appl) assert(appl.tag == "appl") local selector, args, subtemplates = appl.selector, appl.args, appl.subtemplates local env, out, opts = state.env, state.out, state.opts local selector_name = unparse_name(selector) local default if opts.fallback then default = subtemplates[1] end selector = loadstring("local env = (...); return " .. selector)(env) if #subtemplates == 0 then if args and args ~= "" and args ~= "{}" then check_selector(selector_name, selector) selector = selector(loadstring("local env = (...); return " .. args)(env), false) insert(out, tostring(selector)) else if is_callable(selector) then insert(out, tostring(selector())) else if not selector and opts.passthrough then selector = selector_name end insert(out, tostring(selector or "")) end end else if args and args ~= "" and args ~= "{}" then check_selector(selector_name, selector) args = loadstring("local env = (...); return " .. args)(env) for e, literal in coroutine.wrap(selector), args, true do if literal then insert(out, tostring(e)) else if type(e) ~= "table" then e = prepare_env({ it = tostring(e) }, env) else e = prepare_env(e, env) end interpreter.template({ env = e, out = out, opts = opts }, subtemplates[e.self._template or 1] or default) end end else if type(selector) == 'table' then for _, e in ipairs(selector) do if type(e) ~= "table" then e = prepare_env({ it = tostring(e) }, env) else e = prepare_env(e, env) end interpreter.template({ env = e, out = out, opts = opts }, subtemplates[e.self._template or 1] or default) end else check_selector(selector_name, selector) for e, literal in coroutine.wrap(selector), nil, true do if literal then insert(out, tostring(e)) else if type(e) ~= "table" then e = prepare_env({ it = tostring(e) }, env) else e = prepare_env(e, env) end interpreter.template({ env = e, out = out, opts = opts }, subtemplates[e.self._template or 1] or default) end end end end end end function interpreter.template(state, template) if template then assert(template.tag == "template") for _, part in ipairs(template.parts) do interpreter[part.tag](state, part) end end end function fill(template, env, opts) opts = opts or {} local out = opts.out or {} grammar.ast = opts.parser or grammar.default if type(env) == "string" then env = { it = env } end interpreter.template({ env = env, out = out, opts = opts }, grammar.ast:match(template)) return concat(out, opts.delim) end return _ENV lua-cosmo-13.01.30/src/cosmo/grammar.lua000066400000000000000000000117171207723746400177210ustar00rootroot00000000000000 local lpeg = require "lpeg" local re = require "re" if _VERSION == "Lua 5.2" then _ENV = setmetatable({}, { __index = _G }) else module(..., package.seeall) _ENV = _M end local function parse_selector(selector, env) env = env or "env" selector = string.sub(selector, 2, #selector) local parts = {} for w in string.gmatch(selector, "[^|]+") do local n = tonumber(w) if n then table.insert(parts, "[" .. n .. "]") else table.insert(parts, "['" .. w .. "']") end end return env .. table.concat(parts) end local function parse_exp(exp) return exp end local start = "[" * lpeg.P"="^1 * "[" local start_ls = "[" * lpeg.P"="^0 * "[" local longstring1 = lpeg.P{ "longstring", longstring = lpeg.P"[[" * (lpeg.V"longstring" + (lpeg.P(1) - lpeg.P"]]"))^0 * lpeg.P"]]" } local longstring2 = lpeg.P(function (s, i) local l = lpeg.match(start, s, i) if not l then return nil end local p = lpeg.P("]" .. string.rep("=", l - i - 2) .. "]") p = (1 - p)^0 * p return lpeg.match(p, s, l) end) local longstring = #("[" * lpeg.S"[=") * (longstring1 + longstring2) local function parse_longstring(s) local start = s:match("^(%[=*%[)") if start then return string.format("%q", s:sub(#start + 1, #s - #start)) else return s end end local alpha = lpeg.R('__','az','AZ','\127\255') local n = lpeg.R'09' local alphanum = alpha + n local name = alpha * (alphanum)^0 local number = (lpeg.P'.' + n)^1 * (lpeg.S'eE' * lpeg.S'+-'^-1)^-1 * (alphanum)^0 number = #(n + (lpeg.P'.' * n)) * number local shortstring = (lpeg.P'"' * ( (lpeg.P'\\' * 1) + (1 - (lpeg.S'"\n\r\f')) )^0 * lpeg.P'"') + (lpeg.P"'" * ( (lpeg.P'\\' * 1) + (1 - (lpeg.S"'\n\r\f")) )^0 * lpeg.P"'") local space = (lpeg.S'\n \t\r\f')^0 local function syntax(lbra, rbra) return [[ template <- (* -> {} !.) -> compiletemplate item <- / / (. => error) text <- ({~ (! ('$$' -> '$' / .))+ ~}) -> compiletext selector <- ('$]] .. lbra .. [[' %s {~ ~} %s ']] .. rbra .. [[') -> parseexp / ('$' %alphanum+ ('|' %alphanum+)*) -> parseselector templateappl <- ({~ ~} {~ ? ~} !'{' ({%longstring} -> compilesubtemplate)? (%s ','? %s ({%longstring} -> compilesubtemplate))* -> {} !(','? %s %start)) -> compileapplication args <- '{' %s '}' / '{' %s %s (',' %s %s)* ','? %s '}' arg <- / attr <- %s '=' !'=' %s / '[' !'[' !'=' %s %s ']' %s '=' %s symbol <- %alpha %alphanum* explist <- (%s ',' %s )* (%s ',')? exp <- (%s %s )* simpleexp <- / %string / %longstring -> parsels / %number / 'true' / 'false' / 'nil' / %s / / (. => error) unop <- '-' / 'not' / '#' binop <- '+' / '-' / '*' / '/' / '^' / '%' / '..' / '<=' / '<' / '>=' / '>' / '==' / '~=' / 'and' / 'or' prefixexp <- ( / {%name} -> addenv / '(' %s %s ')' ) ( %s / '.' %name / ':' %name %s ('(' %s ')' / '(' %s %s ')') / '[' %s %s ']' / '(' %s ')' / '(' %s %s ')' / %string / %longstring -> parsels %s )* ]] end local function pos_to_line(str, pos) local s = str:sub(1, pos) local line, start = 1, 0 local newline = string.find(s, "\n") while newline do line = line + 1 start = newline newline = string.find(s, "\n", newline + 1) end return line, pos - start end local function ast_text(text) return { tag = "text", text = text } end local function ast_template_application(selector, args, ast_first_subtemplate, ast_subtemplates) if not ast_subtemplates then ast_first_subtemplate = nil end local subtemplates = { ast_first_subtemplate, unpack(ast_subtemplates or {}) } return { tag = "appl", selector = selector, args = args, subtemplates = subtemplates } end local function ast_template(parts) return { tag = "template", parts = parts } end local function ast_subtemplate(text) local start = text:match("^(%[=*%[)") if start then text = text:sub(#start + 1, #text - #start) end return ast:match(text) end local syntax_defs = { start = start_ls, alpha = alpha, alphanum = alphanum, name = name, number = number, string = shortstring, longstring = longstring, s = space, parseselector = parse_selector, parseexp = parse_exp, parsels = parse_longstring, addenv = function (s) return "env['" .. s .. "']" end, error = function (tmpl, pos) local line, pos = pos_to_line(tmpl, pos) error("syntax error in template at line " .. line .. " position " .. pos) end, compiletemplate = ast_template, compiletext = ast_text, compileapplication = ast_template_application, compilesubtemplate = ast_subtemplate } function new(lbra, rbra) lbra = lbra or "(" rbra = rbra or ")" return re.compile(syntax(lbra, rbra), syntax_defs) end default = new() return _ENV lua-cosmo-13.01.30/tests/000077500000000000000000000000001207723746400150145ustar00rootroot00000000000000lua-cosmo-13.01.30/tests/test_cosmo.lua000066400000000000000000000522751207723746400177110ustar00rootroot00000000000000local cosmo = require"cosmo" local grammar = require"cosmo.grammar" values = { rank="Ace", suit="Spades" } template = "$rank of $suit" result = cosmo.fill(template, values) assert(result== "Ace of Spades") mycards = { {rank="Ace", suit="Spades"}, {rank="Queen", suit="Diamonds"}, {rank="10", suit="Hearts"} } template = "$do_cards[[$rank of $suit, ]]" result = cosmo.fill(template, {do_cards = mycards}) assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts, ") result= cosmo.f(template){do_cards = mycards} assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts, ") mycards = { {"Ace", "Spades"}, {"Queen", "Diamonds"}, {"10", "Hearts"} } result = cosmo.f(template){ do_cards = function() for i,v in ipairs(mycards) do cosmo.yield{rank=v[1], suit=v[2]} end end } assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts, ") table.insert(mycards, {"2", "Clubs"}) template = "You have: $do_cards[[$rank of $suit]],[[, $rank of $suit]],[[, and $rank of $suit]]" result = cosmo.f(template){ do_cards = function() for i,v in ipairs(mycards) do local template if i == #mycards then -- for the last item use the third template (with "and") template = 3 elseif i~=1 then -- use the second template for items 2...n-1 template = 2 end cosmo.yield{rank=v[1], suit=v[2], _template=template} end end } assert(result=="You have: Ace of Spades, Queen of Diamonds, 10 of Hearts, and 2 of Clubs") template = "$do_cards[[$1 of $2]]" result= cosmo.f(template){do_cards = cosmo.make_concat(mycards)} assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts, 2 of Clubs") template = "$concat{cards}[[$1 of $2]]" result= cosmo.f(template){cards = mycards, concat = cosmo.concat} assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts, 2 of Clubs") result= cosmo.f(template){cards = mycards, concat = cosmo.concat} assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts, 2 of Clubs") template = "$do_cards[[$it]]" result= cosmo.f(template){do_cards = cosmo.make_concat{ "Ace of Spades", "Queen of Diamonds", "10 of Hearts" } } assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts") result= cosmo.f(template){do_cards = cosmo.make_concat{ "Ace of Spades", "Queen of Diamonds", "10 of Hearts" } } assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts") template = "$do_cards[[$it]]" result= cosmo.f(template){do_cards = cosmo.make_concat{ "Ace of Spades" } } assert(result=="Ace of Spades") result= cosmo.f(template){do_cards = cosmo.make_concat{ "Ace of Spades" } } assert(result=="Ace of Spades") template = "$concat{cards}[[$it]]" result= cosmo.f(template){ cards = { "Ace of Spades", "Queen of Diamonds", "10 of Hearts" }, concat = cosmo.concat } assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts") result= cosmo.f(template){ cards = { "Ace of Spades", "Queen of Diamonds", "10 of Hearts" }, concat = cosmo.concat } assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts") template = "$concat{cards}[[$1 of $2]]" result= cosmo.f(template){cards = mycards, concat = cosmo.concat} assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts, 2 of Clubs") result= cosmo.f(template){cards = mycards, concat = cosmo.concat} assert(result=="Ace of Spades, Queen of Diamonds, 10 of Hearts, 2 of Clubs") template = "$do_cards{'; '}[[$1 of $2]]" result= cosmo.f(template){do_cards = cosmo.make_concat(mycards)} assert(result=="Ace of Spades; Queen of Diamonds; 10 of Hearts; 2 of Clubs") result= cosmo.f(template){do_cards = cosmo.make_concat(mycards)} assert(result=="Ace of Spades; Queen of Diamonds; 10 of Hearts; 2 of Clubs") template = "$concat{cards, '; '}[[$1 of $2]]" result= cosmo.f(template){cards = mycards, concat = cosmo.concat} assert(result=="Ace of Spades; Queen of Diamonds; 10 of Hearts; 2 of Clubs") result= cosmo.f(template){cards = mycards, concat = cosmo.concat} assert(result=="Ace of Spades; Queen of Diamonds; 10 of Hearts; 2 of Clubs") template = [====[You have: $do_cards[[$rank of $suit]], [[, $rank of $suit]], [[, and $rank of $suit]]]====] result = cosmo.f(template){ do_cards = function() for i,v in ipairs(mycards) do local template if i == #mycards then -- for the last item use the third template (with "and") template = 3 elseif i~=1 then -- use the second template for items 2...n-1 template = 2 end cosmo.yield{rank=v[1], suit=v[2], _template=template} end end } assert(result=="You have: Ace of Spades, Queen of Diamonds, 10 of Hearts, and 2 of Clubs") players = {"John", "João"} cards = {} cards["John"] = mycards cards["João"] = { {"Ace", "Diamonds"} } template = "$do_players[=[$player has $do_cards[[$rank of $suit]],[[, $rank of $suit]],[[, and $rank of $suit]]\n]=]" result = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, do_cards = function() for i,v in ipairs(cards[p]) do local template if i == #mycards then -- for the last item use the third template (with "and") template = 3 elseif i~=1 then -- use the second template for items 2...n-1 template = 2 end cosmo.yield{rank=v[1], suit=v[2], _template=template} end end } end end } assert(result=="John has Ace of Spades, Queen of Diamonds, 10 of Hearts, and 2 of Clubs\nJoão has Ace of Diamonds\n") players = {"John", "João"} cards = {} cards["John"] = mycards cards["João"] = { {"Ace", "Diamonds"} } template = "$do_players[[$player has $do_cards[[$rank of $suit]],[=[, $rank of $suit]=],[[, and $rank of $suit]]\n]]" result = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, do_cards = function() for i,v in ipairs(cards[p]) do local template if i == #mycards then -- for the last item use the third template (with "and") template = 3 elseif i~=1 then -- use the second template for items 2...n-1 template = 2 end cosmo.yield{rank=v[1], suit=v[2], _template=template} end end } end end } assert(result=="John has Ace of Spades, Queen of Diamonds, 10 of Hearts, and 2 of Clubs\nJoão has Ace of Diamonds\n") template = "$do_players[=[$player$if_john[[$mark]] has $do_cards[[$rank of $suit, ]]\n]=]" result = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, do_cards = function() for i,v in ipairs(cards[p]) do cosmo.yield{rank=v[1], suit=v[2]} end end, if_john = cosmo.c(p=="John"){mark="*"} } end end } assert(result=="John* has Ace of Spades, Queen of Diamonds, 10 of Hearts, 2 of Clubs, \nJoão has Ace of Diamonds, \n") template = "$do_players[=[$do_cards[[$rank of $suit ($player), ]]]=]" result = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, do_cards = function() for i,v in ipairs(cards[p]) do cosmo.yield{rank=v[1], suit=v[2]} end end, } end end } assert(result=="Ace of Spades (John), Queen of Diamonds (John), 10 of Hearts (John), 2 of Clubs (John), Ace of Diamonds (João), ") template = "$do_players[=[$player: $n card$if_plural[[s]] $if_needs_more[[(needs $n more)]]\n]=]" result = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, n = #cards[p], if_plural = cosmo.cond(#cards[p] > 1, {}), if_needs_more = cosmo.cond(#cards[p] < 3, { n = 3-#cards[p] }) } end end } assert(result=="John: 4 cards \nJoão: 1 card (needs 2 more)\n") result = cosmo.f(template){ do_players = function() for i,p in ipairs(players) do cosmo.yield { player = p, n = #cards[p], if_plural = cosmo.c(#cards[p] > 1){}, if_needs_more = cosmo.c(#cards[p] < 3){ n = 3-#cards[p] } } end end } assert(result=="John: 4 cards \nJoão: 1 card (needs 2 more)\n") template = " $foo|bar $foo|1|baz " result = cosmo.fill(template, { foo = { { baz = "World!" }, bar = "Hello" } }) assert(result==" Hello World! ") template = " $(foo.bar) $(foo[1].baz) " result = cosmo.fill(template, { foo = { { baz = "World!" }, bar = "Hello" } }) assert(result==" Hello World! ") template = " $[foo.bar] $[foo[1].baz] " result = cosmo.fill(template, { foo = { { baz = "World!" }, bar = "Hello" } }, { parser = grammar.new("[", "]") }) assert(result==" Hello World! ") template = " $(foo.bar) $(foo[1].baz) " result = cosmo.fill(template, { foo = { { baz = "World!" }, bar = "Hello" } }) assert(result==" Hello World! ") template = " Hello $message{ 'World!' } " result = cosmo.fill(template, { message = function (arg) return arg[1] end }) assert(result==" Hello World! ") template = " Hello $(message){ 'World!' } " result = cosmo.fill(template, { message = function (arg) return arg[1] end }) assert(result==" Hello World! ") template = " Hello $(message){ 'World!' } " result = cosmo.fill(template, { message = function (arg) return arg[1] end }) assert(result==" Hello World! ") template = " Hello $message{ $msg } " result = cosmo.fill(template, { msg = "World!", message = function (arg) return arg[1] end }) assert(result==" Hello World! ") template = " Hello $message{ $(msg) } " result = cosmo.fill(template, { msg = "World!", message = function (arg) return arg[1] end }) assert(result==" Hello World! ") template = " Hello $message{ $(msg) } " result = cosmo.fill(template, { msg = "World!", message = function (arg) return arg[1] end }) assert(result==" Hello World! ") template = " Hello $message{ $msg }[[$it]] " result = cosmo.fill(template, { msg = "World!", message = function (arg) cosmo.yield{ it = arg[1] } end }) assert(result==" Hello World! ") template = " $foo|bar $foo|1|baz " result = cosmo.f(template){ foo = { { baz = "World!" }, bar = "Hello" } } assert(result==" Hello World! ") template = " Hello $message{ 'World!' } " result = cosmo.f(template){ message = function (arg) return arg[1] end } assert(result==" Hello World! ") template = " Hello $message{ $msg } " result = cosmo.f(template){ msg = "World!", message = function (arg) return arg[1] end } assert(result==" Hello World! ") template = " Hello $message{ $msg }[[$it]] " result = cosmo.f(template){ msg = "World!", message = function (arg) cosmo.yield{ it = arg[1] } end } assert(result==" Hello World! ") template = " Hello $message{ $msg } " result = cosmo.f(template){ msg = "World!", message = function (arg, has_block) if has_block then cosmo.yield{ it = arg[1] } else return arg[1] end end } assert(result==" Hello World! ") template = " Hello $message{ $msg }[[$it]] " result = cosmo.f(template){ msg = "World!", message = function (arg, has_block) if has_block then cosmo.yield{ it = arg[1] } else return arg[1] end end } assert(result==" Hello World! ") template = " Hello $message{ $msg } " result = cosmo.fill(template, { msg = "World!", message = function (arg, has_block) if has_block then cosmo.yield{ it = arg[1] } else return arg[1] end end }) assert(result==" Hello World! ") template = " Hello $message{ msg } " result = cosmo.fill(template, { msg = "World!", message = function (arg, has_block) if has_block then cosmo.yield{ it = arg[1] } else return arg[1] end end }) assert(result==" Hello World! ") template = " Hello $message{ msg } " result = cosmo.fill(template, { msg = "World!", message = function (arg, has_block) if has_block then cosmo.yield{ it = arg[1] } else return arg[1] end end }) assert(result==" Hello World! ") template = " Hello $message{ $msg }[[$it]] " result = cosmo.fill(template, { msg = "World!", message = function (arg, has_block) if has_block then cosmo.yield{ it = arg[1] } else return arg[1] end end }) assert(result==" Hello World! ") template = " $message{ greeting = 'Hello', target = 'World' } " result = cosmo.fill(template, { message = function(arg, has_block) if has_block then cosmo.yield{ grt = arg.greeting, tgt = arg.target } else return arg.greeting .. " " .. arg.target .. "!" end end }) assert(result==" Hello World! ") template = " $message{ greeting = 'Hello', target = 'World' } " result = cosmo.f(template){ message = function(arg, has_block) if has_block then cosmo.yield{ grt = arg.greeting, tgt = arg.target } else return arg.greeting .. " " .. arg.target .. "!" end end } assert(result==" Hello World! ") template = " $message{ greeting = 'Hello', target = 'World' }[[$grt $tgt]] " result = cosmo.fill(template, { message = function(arg, has_block) if has_block then cosmo.yield{ grt = arg.greeting, tgt = arg.target } else return arg.greeting .. " " .. arg.target .. "!" end end }) assert(result==" Hello World ") template = " $message{ greeting = 'Hello', target = 'World'}[[$grt $tgt]] " result = cosmo.f(template){ message = function(arg, has_block) if has_block then cosmo.yield{ grt = arg.greeting, tgt = arg.target } else return arg.greeting .. " " .. arg.target .. "!" end end } assert(result==" Hello World ") local env = {} setmetatable(env, { __index = { text = "Hello World!" } }) template = " $show[[$text]] " result = cosmo.fill(template, { show = function () cosmo.yield(env) end }) assert(result == " Hello World! ") result = cosmo.f(template){ show = function () cosmo.yield(env) end } assert(result == " Hello World! ") template = " $map{ 1, 2, 3, 4, 5}[[$it]] " result = cosmo.fill(template, { map = cosmo.map }) assert(result == " 12345 ") result = cosmo.f(template){ map = cosmo.map } assert(result == " 12345 ") template = " $map{ 1, [[foo]], 3, 4, 5}[[$it]] " result = cosmo.fill(template, { map = cosmo.map }) assert(result == " 1foo345 ") result = cosmo.f(template){ map = cosmo.map } assert(result == " 1foo345 ") template = " $map{ 1, 2, 3, 4, 5} " result = cosmo.fill(template, { map = cosmo.map }) assert(result == " 12345 ") result = cosmo.f(template){ map = cosmo.map } assert(result == " 12345 ") template = "$inject{ msg = 'Hello', target = 'World' }[[ $msg $target! ]]" result = cosmo.fill(template, { inject = cosmo.inject }) assert(result == " Hello World! ") result = cosmo.f(template){ inject = cosmo.inject } assert(result == " Hello World! ") template = "$if{ $x + 3 > 4, target = 'World' }[[ Hello $target! ]],[[ Hi $target! ]]" result = cosmo.fill(template, { x = 0, ["if"] = cosmo.cif }) assert(result == " Hi World! ") result = cosmo.f(template){ x = 0, ["if"] = cosmo.cif } assert(result == " Hi World! ") result = cosmo.fill(template, { x = 2, ["if"] = cosmo.cif }) assert(result == " Hello World! ") result = cosmo.f(template){ x = 2, ["if"] = cosmo.cif } assert(result == " Hello World! ") template = "$if{ $x + 3 > 4, target = 'World' }[[ Hello $target! ]]" result = cosmo.fill(template, { x = 0, ["if"] = cosmo.cif }) assert(result == "") result = cosmo.f(template){ x = 0, ["if"] = cosmo.cif } assert(result == "") result = cosmo.fill(template, { x = 2, ["if"] = cosmo.cif }) assert(result == " Hello World! ") result = cosmo.f(template){ x = 2, ["if"] = cosmo.cif } assert(result == " Hello World! ") template = "$if{ $x + 3 > 4, target = 'World' }[[ Hello $target! ]][[ Hi $target! ]]" result = cosmo.fill(template, { x = 0, ["if"] = cosmo.cif }) assert(result == " Hi World! ") result = cosmo.f(template){ x = 0, ["if"] = cosmo.cif } assert(result == " Hi World! ") result = cosmo.fill(template, { x = 2, ["if"] = cosmo.cif }) assert(result == " Hello World! ") result = cosmo.f(template){ x = 2, ["if"] = cosmo.cif } assert(result == " Hello World! ") template = "$if{ $x + 3 > 4, target = 'World' }[[ Hello $target! ]][[ Hi $target! ]]" result = cosmo.fill(template, { x = 0, ["if"] = cosmo.cif }) assert(result == " Hi World! ") result = cosmo.f(template){ x = 0, ["if"] = cosmo.cif } assert(result == " Hi World! ") result = cosmo.fill(template, { x = 2, ["if"] = cosmo.cif }) assert(result == " Hello World! ") result = cosmo.f(template){ x = 2, ["if"] = cosmo.cif } assert(result == " Hello World! ") template = "$if{ x + 3 > 4, target = 'World' }[[ Hello $target! ]],[[ Hi $target! ]]" result = cosmo.fill(template, { x = 0, ["if"] = cosmo.cif }) assert(result == " Hi World! ") result = cosmo.f(template){ x = 0, ["if"] = cosmo.cif } assert(result == " Hi World! ") result = cosmo.fill(template, { x = 2, ["if"] = cosmo.cif }) assert(result == " Hello World! ") result = cosmo.f(template){ x = 2, ["if"] = cosmo.cif } assert(result == " Hello World! ") template = "$if{ $mod($x, 4) == 0, target = 'World' }[[ Hello $target! ]],[[ Hi $target! ]]" result = cosmo.fill(template, { mod = math.fmod, x = 2, ["if"] = cosmo.cif }) assert(result == " Hi World! ") result = cosmo.f(template){ mod = math.fmod, x = 2, ["if"] = cosmo.cif } assert(result == " Hi World! ") result = cosmo.fill(template, { mod = math.fmod, x = 4, ["if"] = cosmo.cif }) assert(result == " Hello World! ") result = cosmo.f(template){ mod = math.fmod, x = 4, ["if"] = cosmo.cif } assert(result == " Hello World! ") template = "$if{ math.fmod(x, 4) == 0, target = 'World' }[[ Hello $target! ]],[[ Hi $target! ]]" result = cosmo.fill(template, { math = math, x = 2, ["if"] = cosmo.cif }) assert(result == " Hi World! ") result = cosmo.f(template){ math = math, x = 2, ["if"] = cosmo.cif } assert(result == " Hi World! ") result = cosmo.fill(template, { math = math, x = 4, ["if"] = cosmo.cif }) assert(result == " Hello World! ") result = cosmo.f(template){ math = math, x = 4, ["if"] = cosmo.cif } assert(result == " Hello World! ") template = "$if{ x == 0, target = 'World' }[[ Hello $target! ]],[[ Hi $target! ]]" result = cosmo.fill(template, { math = math, x = 4, ["if"] = cosmo.cif }) assert(result == " Hi World! ") result = cosmo.f(template){ math = math, x = 4, ["if"] = cosmo.cif } assert(result == " Hi World! ") result = cosmo.fill(template, { math = math, x = 0, ["if"] = cosmo.cif }) assert(result == " Hello World! ") result = cosmo.f(template){ math = math, x = 0, ["if"] = cosmo.cif } assert(result == " Hello World! ") template = "$if{ x(), target = 'World' }[[ Hello $target! ]],[[ Hi $target! ]]" result = cosmo.fill(template, { math = math, x = function () return false end, ["if"] = cosmo.cif }) assert(result == " Hi World! ") result = cosmo.f(template){ math = math, x = function () return false end, ["if"] = cosmo.cif } assert(result == " Hi World! ") result = cosmo.fill(template, { math = math, x = function () return true end, ["if"] = cosmo.cif }) assert(result == " Hello World! ") result = cosmo.f(template){ math = math, x = function () return true end, ["if"] = cosmo.cif } assert(result == " Hello World! ") template = "$lit[[ $msg]]" result = cosmo.fill(template, { lit = function () cosmo.yield("Hello", true) cosmo.yield({ msg = "World" }) cosmo.yield("!", true) end }) assert(result == "Hello World!") result = cosmo.fill(template, { lit = function () cosmo.yield("Hello", true) cosmo.yield({ msg = "World" }) cosmo.yield("!", true) end }) assert(result == "Hello World!") template = "$if{ math.fmod(x, 4) == 0, target = 'World' }[[ Hello $target! ]]" result = cosmo.fill(template, { math = math, x = 2, ["if"] = cosmo.cif }, { fallback = true }) assert(result == " Hello World! ") result = cosmo.f(template)({ math = math, x = 2, ["if"] = cosmo.cif }, { fallback = true }) assert(result == " Hello World! ") template = " $foo " result = cosmo.fill(template, {}) assert(result == " ") result = cosmo.f(template){} assert(result == " ") template = " $bar " result = cosmo.fill(template, {}, { passthrough = true }) assert(result == " $bar ") result = cosmo.f(template)({}, { passthrough = true }) assert(result == " $bar ")