1fennel-reference(5)            Fennel Reference            fennel-reference(5)
2
3
4

NAME

6       fennel-reference - Fennel Reference
7

DESCRIPTION

9       This  document  covers  the  syntax, built-in macros, and special forms
10       recognized by the Fennel compiler.  It does not  include  built-in  Lua
11       functions;  see  the  Lua  reference  manual (https://www.lua.org/manu
12       al/5.1/) or the  Lua  primer  (https://fennel-lang.org/lua-primer)  for
13       that.  This is not an introductory text; see the tutorial (https://fen
14       nel-lang.org/tutorial) for that.  If you already have a  piece  of  Lua
15       code  you  just  want  to  see  translated  to  Fennel,  use antifennel
16       (https://fennel-lang.org/see).
17
18       A macro is a function which runs at compile time  and  transforms  some
19       Fennel  code  into  different Fennel.  A special form (or special) is a
20       primitive construct which emits Lua code directly.  When you  are  cod‐
21       ing,  you  don't  need  to  care  about the difference between built-in
22       macros and special forms; it is an implementation detail.
23
24       Remember that Fennel relies completely on Lua for its runtime.   Every‐
25       thing  Fennel  does happens at compile-time, so you will need to famil‐
26       iarize yourself with Lua's standard library functions.  Thankfully it's
27       much smaller than almost any other language.
28
29       The one exception to this compile-time rule is the fennel.view function
30       which returns a string representation of any Fennel data  suitable  for
31       printing.  But this is not part of the language itself; it is a library
32       function which can be used from Lua just as easily.
33
34       Fennel source code should be UTF-8-encoded text.
35

SYNTAX

37       (parentheses): used to delimit lists, which are primarily used  to  de‐
38       note  calls to functions, macros, and specials, but also can be used in
39       binding contexts to bind to multiple values.  Lists are a  compile-time
40       construct;  they  are  not used at runtime.  For example: (print "hello
41       world")
42
43       {curly brackets}: used to denote key/value table literals, for example:
44       {:a 1 :b 2}
45
46       [square  brackets]: used to denote sequential tables, which can be used
47       for literal data structures and also in specials and macros to  delimit
48       where  new  identifiers  are  introduced, such as argument lists or let
49       bindings.  For example: [1 2 3]
50
51       The syntax for numbers is the same as Lua's  (https://www.lua.org/manu
52       al/5.4/manual.html#3.1),  except  that underscores may be used to sepa‐
53       rate digits for readability.  Non-ASCII digits are not yet supported.
54
55       The syntax for strings uses double-quotes " around  the  string's  con‐
56       tents.  Double quotes inside a string must be escaped with backslashes.
57       The syntax for these is the same  as  Lua's  (https://www.lua.org/manu
58       al/5.4/manual.html#3.1),  except that strings may contain newline char‐
59       acters.  Single-quoted or long bracket strings are not supported.
60
61       Fennel has a lot fewer restrictions on identifiers than  Lua.   Identi‐
62       fiers  are  represented by symbols, but identifiers are not exactly the
63       same as symbols; some symbols are used by macros for things other  than
64       identifiers.   Symbols  may  not  begin with digits or a colon, but may
65       have digits anywhere else.  Beyond that, any unicode characters are ac‐
66       cepted  as  long  as they are not unprintable or whitespace, one of the
67       delimiter characters mentioned above, one of the  a  prefix  characters
68       listed below, or one of these reserved characters:
69
70       • single quote: '
71
72       • tilde: ~
73
74       • semicolon: ;
75
76       • at: @
77
78       Underscores  are  allowed in identifier names, but dashes are preferred
79       as word separators.  By convention, identifiers  starting  with  under‐
80       scores  are  used to indicate that a local is bound but not meant to be
81       used.
82
83       The ampersand character & is allowed in symbols but not in identifiers.
84       This  allows  it to be reserved for macros, like the behavior of &as in
85       destructuring.
86
87       Symbols that contain a dot . or colon : are considered "multi symbols".
88       The  part  of  the  symbol  before the first dot or colon is used as an
89       identifier, and the part after the dot or colon is a field looked up on
90       the local identified.  A colon is only allowed before the final segment
91       of a multi symbol, so x.y:z is valid but a:b.c  is  not.   Colon  multi
92       symbols cannot be used for anything but method calls.
93
94       Fennel  also  supports certain kinds of strings that begin with a colon
95       as long as they don't contain any characters which wouldn't be  allowed
96       in a symbol, for example :fennel-lang.org is a string.
97
98       Spaces, tabs, newlines, vertical tabs, form feeds, and carriage returns
99       are counted as whitespace.  Non-ASCII whitespace characters are not yet
100       supported.
101
102       Certain prefixes are expanded by the parser into longhand equivalents:
103
104#foo expands to (hashfn foo)
105
106`foo expands to (quote foo)
107
108,foo expands to (unquote foo)
109
110       A  semicolon and everything following it up to the end of the line is a
111       comment.
112

FUNCTIONS

114   fn function
115       Creates a function which binds the arguments given  inside  the  square
116       brackets.   Will  accept any number of arguments; ones in excess of the
117       declared ones are ignored, and if not enough arguments are supplied  to
118       cover the declared ones, the remaining ones are given values of nil.
119
120       Example:
121
122              (fn pxy [x y]
123                (print (+ x y)))
124
125       Giving it a name is optional; if one is provided it will be bound to it
126       as a local.  The following mean exactly the same thing;  the  first  is
127       preferred  mostly  for  indentation reasons, but also because it allows
128       recursion:
129
130              (fn pxy [x y]
131                (print (+ x y)))
132
133              (local pxy (fn [x y]
134                           (print (+ x y))))
135
136       Providing a name that's a table field will cause it to be inserted in a
137       table instead of bound as a local:
138
139              (local functions {})
140
141              (fn functions.p [x y z]
142                (print (* x (+ y z))))
143
144              ;; equivalent to:
145              (set functions.p (fn [x y z]
146                                 (print (* x (+ y z)))))
147
148       Like  Lua, functions in Fennel support tail-call optimization, allowing
149       (among other things) functions to recurse  indefinitely  without  over‐
150       flowing the stack, provided the call is in a tail position.
151
152       The  final form in this and all other function forms is used as the re‐
153       turn value.
154
155   lambda/λ nil-checked function
156       Creates a function like fn does, but throws an error at runtime if  any
157       of the listed arguments are nil, unless its identifier begins with ?.
158
159       Example:
160
161              (lambda [x ?y z]
162                (print (- x (* (or ?y 1) z))))
163
164       Note  that the Lua runtime will fill in missing arguments with nil when
165       they are not provided by the caller, so an explicit nil argument is  no
166       different than omitting an argument.
167
168       Programmers coming from other languages in which it is an error to call
169       a function with a different number of arguments than it is defined with
170       often  get  tripped  up by the behavior of fn.  This is where lambda is
171       most useful.
172
173       The lambda, case, case-try, match and  match-try  forms  are  the  only
174       place  where the ?foo notation is used by the compiler to indicate that
175       a nil value is allowed, but it is a useful notation to communicate  in‐
176       tent anywhere a new local is introduced.
177
178       The λ form is an alias for lambda and behaves identically.
179
180   Docstrings and metadata
181       (Since 0.3.0)
182
183       The fn, lambda, λ and macro forms accept an optional docstring.
184
185              (fn pxy [x y]
186                "Print the sum of x and y"
187                (print (+ x y)))
188
189              (λ pxyz [x ?y z]
190                "Print the sum of x, y, and z. If y is not provided, defaults to 0."
191                (print (+ x (or ?y 0) z)))
192
193       These  are  ignored  by default outside of the REPL, unless metadata is
194       enabled from the CLI  (---metadata)  or  compiler  options  {useMetada‐
195       ta=true},  in which case they are stored in a metadata table along with
196       the arglist, enabling viewing function docs via the doc macro.
197
198              ;; this only works in the repl
199              >> ,doc pxy
200              (pxy x y)
201                Print the sum of x and y
202
203       All function metadata will be garbage collected along with the function
204       itself.   Docstrings  and other metadata can also be accessed via func‐
205       tions on the fennel API with fennel.doc and fennel.metadata.
206
207       (Since 1.1.0)
208
209       All forms that accept a docstring will also accept a metadata table  in
210       the same place:
211
212              (fn add [...]
213                {:fnl/docstring "Add arbitrary amount of numbers."
214                 :fnl/arglist [a b & more]}
215                (match (values (select :# ...) ...)
216                  (0) 0
217                  (1 a) a
218                  (2 a b) (+ a b)
219                  (_ a b) (add (+ a b) (select 3 ...))))
220
221       Here the arglist is overridden by that in the metadata table (note that
222       the contents of the table are implicitly quoted).  Calling ,doc command
223       in the REPL prints specified argument list:
224
225              >> ,doc add
226              (add a b & more)
227                Add arbitrary amount of numbers.
228
229       (Since 1.3.0)
230
231       Arbitrary metadata keys are allowed in the metadata table syntax:
232
233              (fn foo []
234                {:deprecated "v1.9.0"
235                 :fnl/docstring "*DEPRECATED* use foo2"}
236                ;; old way to do stuff
237                )
238
239              (fn foo2 [x]
240                {:added "v2.0.0"
241                 :fnl/docstring "Incompatible but better version of foo!"}
242                ;; do stuff better, now with x!
243                x)
244
245       In this example, the deprecated and added keys are used to store a ver‐
246       sion of a hypothetical library on which the functions  were  deprecated
247       or added.  External tooling then can leverage this information by using
248       Fennel's metadata API:
249
250              >> (local {: metadata} (require :fennel))
251              >> (metadata:get foo :deprecated)
252              "v1.9.0"
253              >> (metadata:get foo2 :added)
254              "v2.0.0"
255
256       Such metadata can be any data literal, including tables, with the  only
257       restriction  that there are no side effects.  Fennel's lists are disal‐
258       lowed as metadata values.
259
260       (Since 1.3.1)
261
262       For editing convenience, the metadata table literals are allowed  after
263       docstrings:
264
265              (fn some-function [x ...]
266                "Docstring for some-function."
267                {:fnl/arglist [x & xs]
268                 :other :metadata}
269                (let [xs [...]]
270                  ;; ...
271                  ))
272
273       In this case, the documentation string is automatically inserted to the
274       metadata table by the compiler.
275
276       The whole metadata table can be obtained by calling metadata:get  with‐
277       out the key argument:
278
279              >> (local {: metadata} (require :fennel))
280              >> (metadata:get some-function)
281              {:fnl/arglist ["x" "&" "xs"]
282               :fnl/docstring "Docstring for some-function."
283               :other "metadata"}
284
285       Fennel itself only uses the fnl/docstring and fnl/arglist metadata keys
286       but third-party code can make use of arbitrary keys.
287
288   Hash function literal shorthand
289       (Since 0.3.0)
290
291       It's pretty easy to create function literals, but  Fennel  provides  an
292       even shorter form of functions.  Hash functions are anonymous functions
293       of one form, with implicitly named arguments.  All of the  below  func‐
294       tions are functionally equivalent:
295
296              (fn [a b] (+ a b))
297
298              (hashfn (+ $1 $2)) ; implementation detail; don't use directly
299
300              #(+ $1 $2)
301
302       This style of anonymous function is useful as a parameter to higher or‐
303       der functions.  It's recommended only  for  simple  one-line  functions
304       that get passed as arguments to other functions.
305
306       The  current implementation only allows for hash functions to use up to
307       9 arguments, each named $1 through $9, or those with varargs, delineat‐
308       ed  by  $...  instead of the usual ....  A lone $ in a hash function is
309       treated as an alias for $1.
310
311       Hash functions are defined with the hashfn macro or  special  character
312       #, which wraps its single argument in a function literal.  For example,
313
314              #$3               ; same as (fn [x y z] z)
315              #[$1 $2 $3]       ; same as (fn [a b c] [a b c])
316              #{:a $1 :b $2}    ; same as (fn [a b] {:a a :b b})
317              #$                ; same as (fn [x] x) (aka the identity function)
318              #val              ; same as (fn [] val)
319              #[:one :two $...] ; same as (fn [...] ["one" "two" ...])
320
321       Hash  arguments  can also be used as parts of multisyms.  For instance,
322       #$.foo is a function which will return the value of the  "foo"  key  in
323       its first argument.
324
325       Unlike  regular  functions, there is no implicit do in a hash function,
326       and thus it cannot contain multiple forms without an explicit do.   The
327       body  itself  is directly used as the return value rather than the last
328       element in the body.
329
330   partial partial application
331       Returns a new function which works like its first argument,  but  fills
332       the  first few arguments in place with the given ones.  This is related
333       to currying but different because calling it will call  the  underlying
334       function instead of waiting till it has the "correct" number of args.
335
336       Example:
337
338              (partial (fn [x y] (print (+ x y))) 2)
339
340       This  example  returns  a  function which will print a number that is 2
341       greater than the argument it is passed.
342

BINDING

344   let scoped locals
345       Introduces a new scope in which a given set of local bindings are used.
346
347       Example:
348
349              (let [x 89
350                    y 198]
351                (print (+ x y 12))) ; => 299
352
353       These locals cannot be changed with set but they can be shadowed by  an
354       inner  let  or local.  Outside the body of the let, the bindings it in‐
355       troduces are no longer visible.  The last form in the body is  used  as
356       the return value.
357
358       Any time you bind a local, you can destructure it if the value is a ta‐
359       ble or a function call which returns multiple values:
360
361       Example:
362
363              (let [(x y z) (unpack [10 9 8])]
364                (+ x y z)) ; => 27
365
366       Example:
367
368              (let [[a b c] [1 2 3]]
369                (+ a b c)) ; => 6
370
371       If a table key is a string with the same name as the local you want  to
372       bind  to,  you can use shorthand of just : for the key name followed by
373       the local name.
374
375       Example:
376
377              (let [{:msg message : val} {:msg "hello there" :val 19}]
378                (print message)
379                val) ; prints "hello there" and returns 19
380
381       When destructuring a sequential table, you can capture all the  remain‐
382       der of the table in a local by using &:
383
384       Example:
385
386              (let [[a b & c] [1 2 3 4 5 6]]
387                (table.concat c ",")) ; => "3,4,5,6"
388
389       (Since 1.3.0): This also works with function argument lists, but it has
390       a small performance cost, so it's recommended to  use  ...  instead  in
391       cases that are sensitive to overhead.
392
393       If a table implements __fennelrest metamethod it is used to capture the
394       remainder of the table.  It can be used with custom data structures im‐
395       plemented  in  terms  of  tables, which wish to provide custom rest de‐
396       structuring.  The metamethod receives the table as the first  argument,
397       and the amount of values it needs to drop from the beginning of the ta‐
398       ble, much like table.unpack
399
400       Example:
401
402              (local t [1 2 3 4 5 6])
403              (setmetatable
404               t
405               {:__fennelrest (fn [t k]
406                                (let [res {}]
407                                  (for [i k (length t)]
408                                    (tset res (tostring (. t i)) (. t i)))
409                                res))})
410              (let [[a b & c] t]
411                c) ;; => {:3 3 :4 4 :5 5 :6 6}
412
413       When destructuring a non-sequential table, you can capture the original
414       table along with the destructuring by using &as:
415
416       Example:
417
418              (let [{:a a :b b &as all} {:a 1 :b 2 :c 3 :d 4}]
419                (+ a b all.c all.d)) ; => 10
420
421   local declare local
422       Introduces  a  new  local inside an existing scope.  Similar to let but
423       without a body argument.  Recommended for use at  the  top-level  of  a
424       file for locals which will be used throughout the file.
425
426       Example:
427
428              (local tau-approx 6.28318)
429
430       Supports destructuring and multiple-value binding.
431
432   case pattern matching
433       (Since 1.3.0)
434
435       Evaluates  its  first  argument, then searches thru the subsequent pat‐
436       tern/body clauses to find one where the pattern matches the value,  and
437       evaluates  the  corresponding body.  Pattern matching can be thought of
438       as a combination of destructuring and conditionals.
439
440       Note: Lua also has "patterns" which are matched against strings similar
441       to  how regular expressions work in other languages; these are two dis‐
442       tinct concepts with similar names.
443
444       Example:
445
446              (case mytable
447                59      :will-never-match-hopefully
448                [9 q 5] (print :q q)
449                [1 a b] (+ a b))
450
451       In the example above, we have a mytable value followed  by  three  pat‐
452       tern/body clauses.
453
454       The first clause will only match if mytable is 59.
455
456       The  second clause will match if mytable is a table with 9 as its first
457       element, any non-nil value as its second value and 5 as its third  ele‐
458       ment; if it matches, then it evaluates (print :q q) with q bound to the
459       second element of mytable.
460
461       The final clause will only match if mytable has 1 as its first  element
462       and  two  non-nil values after it; if so then it will add up the second
463       and third elements.
464
465       If no clause matches, the form evaluates to nil.
466
467       Patterns can be tables, literal values, or symbols.  Any symbol is  im‐
468       plicitly  checked to be not nil.  Symbols can be repeated in an expres‐
469       sion to check for the same value.
470
471       Example:
472
473              (case mytable
474                ;; the first and second values of mytable are not nil and are the same value
475                [a a] (* a 2)
476                ;; the first and second values are not nil and are not the same value
477                [a b] (+ a b))
478
479       It's important to note that expressions are checked in  order!  In  the
480       above  example,  since [a a] is checked first, we can be confident that
481       when [a b] is checked, the two values must be different.  Had the order
482       been  reversed,  [a  b] would always match as long as they're not nil -
483       even if they have the same value!
484
485       You may allow a symbol to optionally be nil by prefixing it with ?.
486
487       Example:
488
489              (case mytable
490                ;; not-nil, maybe-nil
491                [a ?b] :maybe-one-maybe-two-values
492                ;; maybe-nil == maybe-nil, both are nil or both are the same value
493                [?a ?a] :maybe-none-maybe-two-same-values
494                ;; maybe-nil, maybe-nil
495                [?a ?b] :maybe-none-maybe-one-maybe-two-values)
496
497       Symbols prefixed by an _ are ignored and may  stand  in  as  positional
498       placeholders  or  markers  for  "any" value - including a nil value.  A
499       single _ is also often used at the end of a case expression  to  define
500       an "else" style fall-through value.
501
502       Example:
503
504              (case mytable
505                ;; not-nil, anything
506                [a _b] :maybe-one-maybe-two-values
507                ;; anything, anything (different to the previous ?a example!)
508                ;; note this is effectively the same as []
509                [_a _a] :maybe-none-maybe-one-maybe-two-values
510                ;; anything, anything
511                ;; this is identical to [_a _a] and in this example would never actually match.
512                [_a _b] :maybe-none-maybe-one-maybe-two-values
513                ;; when no other clause matched, in this case any non-table value
514                _ :no-match)
515
516       Tables  can  be nested, and they may be either sequential ([] style) or
517       key/value ({} style) tables.  Sequential tables will match if they have
518       at  least  as many elements as the pattern.  (To allow an element to be
519       nil, see ? and _ as above.)  Tables will never fail  to  match  due  to
520       having too many elements - this means [] matches any table, not an emp‐
521       ty table.  You can use & to capture all the remaining elements of a se‐
522       quential table, just like let.
523
524              (case mytable
525                {:subtable [a b ?c] :depth depth} (* b depth)
526                _ :unknown)
527
528       You  can  also  match against multiple return values using parentheses.
529       (These cannot be nested, but they can contain  tables.)   This  can  be
530       useful for error checking.
531
532              (case (io.open "/some/file")
533                (nil msg) (report-error msg)
534                f (read-file f))
535
536   Guard Clauses
537       Sometimes  you need to match on something more general than a structure
538       or specific value.  In these cases you can use guard clauses:
539
540              (case [91 12 53]
541                (where [a b c] (= 5 a)) :will-not-match
542                (where [a b c] (= 0 (math.fmod (+ a b c) 2)) (= 91 a)) c) ; -> 53
543
544       In this case the pattern should be wrapped in  parentheses  (like  when
545       matching  against multiple values) but the first thing in the parenthe‐
546       ses is the where symbol.  Each form after the pattern is  a  condition;
547       all the conditions must evaluate to true for that pattern to match.
548
549       If  several  patterns share the same body and guards, such patterns can
550       be combined with or special in the where clause:
551
552              (case [5 1 2]
553                (where (or [a 3 9] [a 1 2]) (= 5 a)) "Either [5 3 9] or [5 1 2]"
554                _ "anything else")
555
556       This is essentially equivalent to:
557
558              (case [5 1 2]
559                (where [a 3 9] (= 5 a)) "Either [5 3 9] or [5 1 2]"
560                (where [a 1 2] (= 5 a)) "Either [5 3 9] or [5 1 2]"
561                _ "anything else")
562
563       However, patterns which bind variables should not be combined  with  or
564       if  different  variables  are bound in different patterns or some vari‐
565       ables are missing:
566
567              ;; bad
568              (case [1 2 3]
569                ;; Will throw an error because `b' is nil for the first
570                ;; pattern but the guard still uses it.
571                (where (or [a 1 2] [a b 3]) (< a 0) (< b 1))
572                :body)
573
574              ;; ok
575              (case [1 2 3]
576                (where (or [a b 2] [a b 3]) (< a 0) (<= b 1))
577                :body)
578
579   Binding Pinning
580       Symbols bound inside a case pattern are independent from  any  existing
581       symbols  in  the  current scope, that is - names may be re-used without
582       consequence.
583
584       Example:
585
586              (let [x 1]
587                (case [:hello]
588                  ;; `x` is simply bound to the first value of [:hello]
589                  [x] x)) ; -> :hello
590
591       Sometimes it may be desirable to match against an existing value in the
592       outer scope.  To do this we can "pin" a binding inside the pattern with
593       an existing outer binding with the unary (=  binding-name)  form.   The
594       unary (= binding-name) form is only valid in a case pattern and must be
595       inside a (where) guard.
596
597       Example:
598
599              (let [x 1]
600                (case [:hello]
601                  ;; 1 != :hello
602                  (where [(= x)]) x
603                  _ :no-match)) ; -> no-match
604
605              (let [x 1]
606                (case [1]
607                  ;; 1 == 1
608                  (where [(= x)]) x
609                  _ :no-match)) ; -> 1
610
611              (let [pass :hunter2]
612                (case (user-input)
613                  (where (= pass)) :login
614                  _ :try-again!))
615
616       Pinning is only required inside the pattern.  Outer bindings are  auto‐
617       matically  available  inside  guards and bodies as long as the name has
618       not been rebound in the pattern.
619
620       Note: The case macro can be used in place of the if-let macro from Clo‐
621       jure.   The reason Fennel doesn't have if-let is that case makes it re‐
622       dundant.
623
624   match pattern matching
625       (since 0.2.0)
626
627       match is conceptually equivalent to case, except symbols  in  the  pat‐
628       terns are always pinned with outer-scope symbols if they exist.
629
630       It supports all the same syntax as described in case except the pin ((=
631       binding-name)) expression, as it is always performed.
632
633              Be careful when using match that your symbols are  not  acciden‐
634              tally  the  same as any existing symbols!  If you know you don't
635              intend to pin any existing symbols you should use the  case  ex‐
636              pression.
637
638              (let [x 95]
639               (match [52 85 95]
640                 [b a a] :no ; because a=85 and a=95
641                 [x y z] :no ; because x=95 and x=52
642                 [a b x] :yes)) ; a and b are fresh values while x=95 and x=95
643
644       Unlike  in case, if an existing binding has the value nil, the ? prefix
645       is not necessary - it would instead create a new un-pinned binding!
646
647       Example:
648
649              (let [name nil
650                    get-input (fn [] "Dave")]
651                (match (get-input)
652                  ;; name already exists as nil, "Dave" != nil so this *wont* match
653                  name (.. "Hello " name)
654                  ?no-input (.. "Hello anonymous"))) ; -> "Hello anonymous"
655
656       Note: The match macro can be used in place of  the  if-let  macro  from
657       Clojure.   The reason Fennel doesn't have if-let is that match makes it
658       redundant.
659
660       Note 2: Prior to Fennel 0.9.0 the match macro used infix ? operator  to
661       test  patterns against the guards.  While this syntax is still support‐
662       ed, where should be preferred instead:
663
664              (match [1 2 3]
665                (where [a 2 3] (< 0 a)) "new guard syntax"
666                ([a 2 3] ? (< 0 a)) "obsolete guard syntax")
667
668   case-try for matching multiple steps
669       Evaluates a series of pattern matching steps.  The value from the first
670       expression  is  matched  against the first pattern.  If it matches, the
671       first body is evaluated and its value is  matched  against  the  second
672       pattern, etc.
673
674       If  there  is  a (catch pat1 body1 pat2 body2 ...) form at the end, any
675       mismatch from the steps will be tried against  these  patterns  in  se‐
676       quence  as  a  fallback  just  like a normal case.  If no catch pattern
677       matches, nil is returned.
678
679       If there is no catch, the mismatched value will be returned as the val‐
680       ue of the entire expression.
681
682              (fn handle [conn token]
683                (case-try (conn:receive :*l)
684                  input (parse input)
685                  (command-name params (= token)) (commands.get command-name)
686                  command (pcall command (table.unpack params))
687                  (catch
688                   (_ :timeout) nil
689                   (_ :closed) (pcall disconnect conn "connection closed")
690                   (_ msg) (print "Error handling input" msg))))
691
692       This is useful when you want to perform a series of steps, any of which
693       could fail.  The catch clause lets you keep all your error handling  in
694       one  place.  Note that there are two ways to indicate failure in Fennel
695       and Lua: using the assert/error functions or returning nil followed  by
696       some  data  representing the failure.  This form only works on the lat‐
697       ter, but you can use pcall to transform error calls into values.
698
699   match-try for matching multiple steps
700       Equivalent to case-try but uses match internally.  See case  and  match
701       for details on the differences between these two forms.
702
703       Unlike  case-try, match-try will pin values in a given catch block with
704       those in the original steps.
705
706              (fn handle [conn token]
707                (match-try (conn:receive :*l)
708                  input (parse input)
709                  (command-name params token) (commands.get command-name)
710                  command (pcall command (table.unpack params))
711                  (catch
712                    (_ :timeout) nil
713                    (_ :closed) (pcall disconnect conn "connection closed")
714                    (_ msg) (print "Error handling input" msg))))
715
716   var declare local variable
717       Introduces a new local inside an existing scope which may have its val‐
718       ue changed.  Identical to local apart from allowing set to work on it.
719
720       Example:
721
722              (var x 83)
723
724       Supports destructuring and multiple-value binding.
725
726   set set local variable or table field
727       Changes  the value of a variable introduced with var.  Will not work on
728       globals or let/local-bound locals.  Can also be used to change a  field
729       of  a table, even if the table is bound with let or local, provided the
730       field is given at compile-time.
731
732       Example:
733
734              (set x (+ x 91))
735
736       Example:
737
738              (let [t {:a 4 :b 8}]
739                (set t.a 2) t) ; => {:a 2 :b 8}
740
741       Supports destructuring and multiple-value binding.
742
743   tset set table field
744       Sets the field of a given table to a new value.  The  field  name  does
745       not  need  to  be known at compile-time.  Works on any table; the table
746       does not have to be declared with var to change its fields.
747
748       Example:
749
750              (let [tbl {:d 32} field :d]
751                (tset tbl field 19) tbl) ; => {:d 19}
752
753       You can provide multiple successive field names to perform nested sets.
754       For example:
755
756              (let [tbl {:a {:b {}}} field :c]
757                (tset tbl :a :b field "d") tbl) ; => {:a {:b {:c "d"}}}
758
759   multiple value binding
760       In  any of the above contexts where you can make a new binding, you can
761       use multiple value binding.  Otherwise you will only capture the  first
762       value.
763
764       Example:
765
766              (let [x (values 1 2 3)]
767                x) ; => 1
768
769       Example:
770
771              (let [(file-handle message code) (io.open "foo.blah")]
772                message) ; => "foo.blah: No such file or directory"
773
774       Example:
775
776              (do (local (_ _ z) (unpack [:a :b :c :d :e])) z)  => c
777
778   with-open bind and auto-close file handles
779       (Since 0.4.2)
780
781       While  Lua  will  automatically  close  an  open  file handle when it's
782       garbage collected, GC may not run right away; with-open ensures handles
783       are closed immediately, error or no, without boilerplate.
784
785       The usage is similar to let, except:
786
787       • destructuring is disallowed (symbols only on the left-hand side)
788
789       • every  binding  should  be a file handle or other value with a :close
790         method.
791
792       After executing the body, or upon encountering an error, with-open will
793       invoke  (value:close)  on every bound variable before returning the re‐
794       sults.
795
796       The body is implicitly wrapped in a function and  run  with  xpcall  so
797       that all bound handles are closed before it re-raises the error.
798
799       Example:
800
801              ;; Basic usage
802              (with-open [fout (io.open :output.txt :w) fin (io.open :input.txt)]
803                (fout:write "Here is some text!\n")
804                ((fin:lines))) ; => first line of input.txt
805
806              ;; This demonstrates that the file will also be closed upon error.
807              (var fh nil)
808              (local (ok err)
809                (pcall #(with-open [file (io.open :test.txt :w)]
810                          (set fh file) ; you would normally never do this
811                          (error :whoops!))))
812              (io.type fh) ; => "closed file"
813              [ok err]     ; => [false "<error message and stacktrace>"]
814
815   pick-values emit exactly n values
816       (Since 0.4.0)
817
818       Discards  all  values  after the first n when dealing with multi-values
819       (...) and multiple returns.  Useful for composing functions that return
820       multiple  values  with variadic functions.  Expands to a let expression
821       that binds and re-emits exactly n values, e.g.
822
823              (pick-values 2 (func))
824
825       expands to
826
827              (let [(_0_ _1_) (func)] (values _0_ _1_))
828
829       Example:
830
831              (pick-values 0 :a :b :c :d :e) ; => nil
832              [(pick-values 2 (table.unpack [:a :b :c]))] ;-> ["a" "b"]
833
834              (fn add [x y ...] (let [sum (+ (or x 0) (or y 0))]
835                                      (if (= (select :# ...) 0) sum (add sum ...))))
836
837              (add (pick-values 2 10 10 10 10)) ; => 20
838              (->> [1 2 3 4 5] (table.unpack) (pick-values 3) (add)) ; => 6
839
840       Note: If n is greater than the number of values supplied, n values will
841       still  be  emitted.   This  is reflected when using (select "#" ...) to
842       count varargs, but tables [...] ignore trailing nils:
843
844              (select :# (pick-values 5 "one" "two")) ; => 5
845              [(pick-values 5 "one" "two")]           ; => ["one" "two"]
846

FLOW CONTROL

848   if conditional
849       Checks a condition and evaluates a  corresponding  body.   Accepts  any
850       number of condition/body pairs; if an odd number of arguments is given,
851       the last value is treated as a catch-all "else".  Similar  to  cond  in
852       other lisps.
853
854       Example:
855
856              (let [x (math.random 64)]
857                (if (= 0 (% x 10))
858                    "multiple of ten"
859                    (= 0 (% x 2))
860                    "even"
861                    "I dunno, something else"))
862
863       All values other than nil or false are treated as true.
864
865   when single side-effecting conditional
866       Takes  a  single condition and evaluates the rest as a body if it's not
867       nil or false.  This is intended for side-effects.  The last form in the
868       body is used as the return value.
869
870       Example:
871
872              (when launch-missiles?
873                (power-on)
874                (open-doors)
875                (fire))
876
877   each general iteration
878       Runs  the  body once for each value provided by the iterator.  Commonly
879       used with ipairs (for sequential tables) or pairs (for any table in un‐
880       defined order) but can be used with any iterator.  Returns nil.
881
882       Example:
883
884              (each [key value (pairs mytbl)]
885                (print "executing key")
886                (print (f value)))
887
888       Any loop can be terminated early by placing an &until clause at the end
889       of the bindings:
890
891              (local out [])
892              (each [_ value (pairs tbl) &until (< max-len (length out))]
893                (table.insert out value))
894
895       Note: prior to fennel version 1.2.0, :until was used instead of &until;
896       the old syntax is still supported for backwards compatibility.
897
898       Most  iterators  return two values, but each will bind any number.  See
899       Programming in Lua (https://www.lua.org/pil/7.1.html) for details about
900       how iterators work.
901
902   for numeric loop
903       Counts  a number from a start to stop point (inclusive), evaluating the
904       body once for each value.  Accepts an optional step.  Returns nil.
905
906       Example:
907
908              (for [i 1 10 2]
909                (log-number i)
910                (print i))
911
912       This example will print all odd numbers under ten.
913
914       Like each, loops using for can also be terminated early with an  &until
915       clause.  The clause is checked before each iteration of the body; if it
916       is true at the beginning then the body will not run at all.
917
918              (var x 0)
919              (for [i 1 128 &until (maxed-out? x)]
920                (set x (+ x i)))
921
922   while good old while loop
923       Loops over a body until a condition is met.  Uses a  native  Lua  while
924       loop.  Returns nil.
925
926       Example:
927
928              (var done? false)
929              (while (not done?)
930                (print :not-done)
931                (when (< 0.95 (math.random))
932                  (set done? true)))
933
934   do evaluate multiple forms returning last value
935       Accepts any number of forms and evaluates all of them in order, return‐
936       ing the last value.  This is used for  inserting  side-effects  into  a
937       form which accepts only a single value, such as in a body of an if when
938       multiple clauses make it so you can't use when.  Some lisps  call  this
939       begin or progn.
940
941              (if launch-missiles?
942                  (do
943                    (power-on)
944                    (open-doors)
945                    (fire))
946                  false-alarm?
947                  (promote lt-petrov))
948
949       Some other forms like fn and let have an implicit do.
950

DATA

952   operators
953and, or, not: boolean
954
955+, -, *, /, //, %, ^: arithmetic
956
957>, <, >=, <=, =, not=: comparison
958
959lshift, rshift, band, bor, bxor, bnot: bitwise operations
960
961       These  all  work  as you would expect, with a few caveats.  The bitwise
962       operators are only available in Lua 5.3+, unless you use the --use-bit-
963       lib flag or the useBitLib flag in the options table, which lets them be
964       used in LuaJIT.  The integer division operator (//) is  only  available
965       in Lua 5.3+.
966
967       They  all take any number of arguments, as long as that number is fixed
968       at compile-time.  For instance, (= 2 2 (unpack [2 5])) will evaluate to
969       true  because  the  compile-time  number of values being compared is 3.
970       Multiple values at runtime will not be taken into account.
971
972       Note that these are all special forms which cannot be used  as  higher-
973       order functions.
974
975   .. string concatenation
976       Concatenates  its  arguments into one string.  Will coerce numbers into
977       strings, but not other types.
978
979       Example:
980
981              (.. "Hello" " " "world" 7 "!!!") ; => "Hello world7!!!"
982
983       String concatenation is subject to the same compile-time limit  as  the
984       operators above; it is not aware of multiple values at runtime.
985
986   length string or table length
987       (Changed in 0.3.0: the function was called # before.)
988
989       Returns the length of a string or table.  Note that the length of a ta‐
990       ble with gaps (nils) in it is undefined; it can return a number  corre‐
991       sponding  to  any  of  the table's "boundary" positions between nil and
992       non-nil values.  If a table has nils and you want to know the last con‐
993       secutive  numeric  index  starting at 1, you must calculate it yourself
994       with ipairs; if you want to know the maximum numeric  key  in  a  table
995       with nils, you can use table.maxn.
996
997       Example:
998
999              (+ (length [1 2 3 nil 8]) (length "abc")) ; => 6 or 8
1000
1001   . table lookup
1002       Looks up a given key in a table.  Multiple arguments will perform nest‐
1003       ed lookup.
1004
1005       Example:
1006
1007              (. mytbl myfield)
1008
1009       Example:
1010
1011              (let [t {:a [2 3 4]}] (. t :a 2)) ; => 3
1012
1013       Note that if the field name is a string  known  at  compile  time,  you
1014       don't need this and can just use mytbl.field.
1015
1016   Nil-safe ?. table lookup
1017       Looks up a given key in a table.  Multiple arguments will perform nest‐
1018       ed lookup.  If any of subsequent keys is not present,  will  short-cir‐
1019       cuit to nil.
1020
1021       Example:
1022
1023              (?. mytbl myfield)
1024
1025       Example:
1026
1027              (let [t {:a [2 3 4]}] (?. t :a 4 :b)) ; => nil
1028              (let [t {:a [2 3 4 {:b 42}]}] (?. t :a 4 :b)) ; => 42
1029
1030   icollect, collect table comprehension macros
1031       (Since 0.8.0)
1032
1033       The  icollect macro takes a "iterator binding table" in the format that
1034       each takes, and returns a sequential table containing  all  the  values
1035       produced by each iteration of the macro's body.  This is similar to how
1036       map works in several other languages, but it is a macro,  not  a  func‐
1037       tion.
1038
1039       If  the  value  is  nil,  it is omitted from the return table.  This is
1040       analogous to filter in other languages.
1041
1042              (icollect [_ v (ipairs [1 2 3 4 5 6])]
1043                (if (> v 2) (* v v)))
1044              ;; -> [9 16 25 36]
1045
1046              ;; equivalent to:
1047              (let [tbl []]
1048                (each [_ v (ipairs [1 2 3 4 5 6])]
1049                  (tset tbl (+ (length tbl) 1) (if (> v 2) (* v v))))
1050                tbl)
1051
1052       The collect macro is almost identical, except that the body should  re‐
1053       turn two things: a key and a value.
1054
1055              (collect [k v (pairs {:apple "red" :orange "orange" :lemon "yellow"})]
1056                (if (not= v "yellow")
1057                    (values (.. "color-" v) k)))
1058              ;; -> {:color-orange "orange" :color-red "apple"}
1059
1060              ;; equivalent to:
1061              (let [tbl {}]
1062                (each [k v (pairs {:apple "red" :orange "orange"})]
1063                  (if (not= v "yellow")
1064                    (match (values (.. "color-" v) k)
1065                      (key value) (tset tbl key value))))
1066                tbl)
1067
1068       If  the key and value are given directly in the body of collect and not
1069       nested in an outer form, then the values can be omitted for brevity:
1070
1071              (collect [k v (pairs {:a 85 :b 52 :c 621 :d 44})]
1072                k (* v 5))
1073
1074       Like each and for, the table comprehensions support  an  &until  clause
1075       for early termination.
1076
1077       Both  icollect  and  collect  take an &into clause which allows you put
1078       your results into an existing table instead of starting with  an  empty
1079       one:
1080
1081              (icollect [_ x (ipairs [2 3]) &into [9]]
1082                (* x 11))
1083              ;; -> [9 22 33]
1084
1085       Note:  Prior  to fennel version 1.2.0, :into was used instead of &into;
1086       the old syntax is still supported for backwards compatibility.
1087
1088   accumulate iterator accumulation
1089       (Since 0.10.0)
1090
1091       Runs through an iterator and performs accumulation, similar to fold and
1092       reduce commonly used in functional programming languages.  Like collect
1093       and icollect, it takes an iterator binding table and an  expression  as
1094       its  arguments.   The  difference  is that in accumulate, the first two
1095       items in the binding table are used as an  "accumulator"  variable  and
1096       its initial value.  For each iteration step, it evaluates the given ex‐
1097       pression and its value becomes the next accumulator variable.   accumu‐
1098       late returns the final value of the accumulator variable.
1099
1100       Example:
1101
1102              (accumulate [sum 0
1103                           i n (ipairs [10 20 30 40])]
1104                  (+ sum n)) ; -> 100
1105
1106       The &until clause is also supported here for early termination.
1107
1108   faccumulate range accumulation
1109       (Since 1.3.0)
1110
1111       Identical to accumulate, but instead of taking an iterator and the same
1112       bindings as each, it accepts the same bindings as for and will  iterate
1113       the numerical range.  Accepts &until just like for and accumulate.
1114
1115       Example:
1116
1117              (faccumulate [n 0 i 1 5] (+ n i)) ; => 15
1118
1119   fcollect range comprehension macro
1120       (Since 1.1.1)
1121
1122       Similarly to icollect, fcollect provides a way of building a sequential
1123       table.  Unlike icollect, instead of an iterator it traverses  a  range,
1124       as  accepted by the for special.  The &into and &until clauses work the
1125       same as in icollect.
1126
1127       Example:
1128
1129              (fcollect [i 0 10 2]
1130                (if (> i 2) (* i i)))
1131              ;; -> [16 36 64 100]
1132
1133              ;; equivalent to:
1134              (let [tbl {}]
1135                (for [i 0 10 2]
1136                  (if (> i 2)
1137                      (table.insert tbl (* i i))))
1138                tbl)
1139
1140   values multi-valued return
1141       Returns multiple values from a function.  Usually used to signal  fail‐
1142       ure by returning nil followed by a message.
1143
1144       Example:
1145
1146              (fn [filename]
1147                (if (valid-file-name? filename)
1148                    (open-file filename)
1149                    (values nil (.. "Invalid filename: " filename))))
1150

OTHER

1152   : method call
1153       Looks up a function in a table and calls it with the table as its first
1154       argument.  This is a common idiom in  many  Lua  APIs,  including  some
1155       built-in ones.
1156
1157       (Since 0.3.0) Just like Lua, you can perform a method call by calling a
1158       function name where : separates the table variable and method name.
1159
1160       Example:
1161
1162              (let [f (assert (io.open "hello" "w"))]
1163                (f:write "world")
1164                (f:close))
1165
1166       If the name of the method isn't known at compile time, you  can  use  :
1167       followed by the table and then the method's name as a string.
1168
1169       Example:
1170
1171              (let [f (assert (io.open "hello" "w"))
1172                    method1 :write
1173                    method2 :close]
1174                (: f method1 "world")
1175                (: f method2))
1176
1177       Both of these examples are equivalent to the following:
1178
1179              (let [f (assert (io.open "hello" "w"))]
1180                (f.write f "world")
1181                (f.close f))
1182
1183       Unlike  Lua,  there's nothing special about defining functions that get
1184       called this way; typically it is given an extra  argument  called  self
1185       but this is just a convention; you can name it anything.
1186
1187              (local t {})
1188
1189              (fn t.enable [self]
1190                (set self.enabled? true))
1191
1192              (t:enable)
1193
1194   ->, ->>, -?> and -?>> threading macros
1195       The  -> macro takes its first value and splices it into the second form
1196       as the first argument.  The result of evaluating the second  form  gets
1197       spliced into the first argument of the third form, and so on.
1198
1199       Example:
1200
1201              (-> 52
1202                  (+ 91 2) ; (+ 52 91 2)
1203                  (- 8)    ; (- (+ 52 91 2) 8)
1204                  (print "is the answer")) ; (print (- (+ 52 91 2) 8) "is the answer")
1205
1206       The  ->> macro works the same, except it splices it into the last posi‐
1207       tion of each form instead of the first.
1208
1209       -?> and -?>>, the thread maybe macros, are similar to -> & ->> but they
1210       also  do  checking  after the evaluation of each threaded form.  If the
1211       result is false or nil then the threading stops and the result  is  re‐
1212       turned.  -?> splices the threaded value as the first argument, like ->,
1213       and -?>> splices it into the last position, like ->>.
1214
1215       This example shows how to use them to avoid accidentally indexing a nil
1216       value:
1217
1218              (-?> {:a {:b {:c 42}}}
1219                   (. :a)
1220                   (. :missing)
1221                   (. :c)) ; -> nil
1222              (-?>> :a
1223                    (. {:a :b})
1224                    (. {:b :missing})
1225                    (. {:c 42})) ; -> nil
1226
1227       While  ->  and  ->>  pass multiple values thru without any trouble, the
1228       checks in -?> and -?>> prevent the same from  happening  there  without
1229       performance overhead, so these pipelines are limited to a single value.
1230
1231              Note  that these have nothing to do with "threads" used for con‐
1232              currency; they are named after  the  thread  which  is  used  in
1233              sewing.   This  is similar to the way that |> works in OCaml and
1234              Elixir.
1235
1236   doto
1237       Similarly, the doto macro  splices  the  first  value  into  subsequent
1238       forms.   However,  it  keeps the same value and continually splices the
1239       same thing in rather than using the value from the  previous  form  for
1240       the next form.
1241
1242              (doto (io.open "/tmp/err.log")
1243                (: :write contents)
1244                (: :close))
1245
1246              ;; equivalent to:
1247              (let [x (io.open "/tmp/err.log")]
1248                (: x :write contents)
1249                (: x :close)
1250                x)
1251
1252       The  first  form becomes the return value for the whole expression, and
1253       subsequent forms are evaluated solely for side-effects.
1254
1255   include
1256       (since 0.3.0)
1257
1258              (include :my.embedded.module)
1259
1260       Loads Fennel/Lua module code at compile time and embeds it in the  com‐
1261       piled  output.  The module name must resolve to a string literal during
1262       compilation.  The bundled code will be wrapped in a function invocation
1263       in the emitted Lua and set on package.preload[modulename]; a normal re‐
1264       quire is then emitted where include was used to load it on demand as  a
1265       normal module.
1266
1267       In  most  cases it's better to use require in your code and use the re‐
1268       quireAsInclude option in the API documentation and the --require-as-in‐
1269       clude CLI flag (fennel --help) to accomplish this.
1270
1271       The  require function is not part of Fennel; it comes from Lua.  Howev‐
1272       er, it works to load Fennel code.  See the Modules and  multiple  files
1273       section     in     the     tutorial     and    Programming    in    Lua
1274       (https://www.lua.org/pil/8.1.html) for details about require.
1275
1276       Starting from version 0.10.0  include  and  hence  --require-as-include
1277       support  semi-dynamic compile-time resolution of module paths similarly
1278       to import-macros.  See the relative require section in the tutorial for
1279       more information.
1280

MACROS

1282       All  forms which introduce macros do so inside the current scope.  This
1283       is usually the top level for a given file, but you can introduce macros
1284       into  smaller scopes as well.  Note that macros are a compile-time con‐
1285       struct; they do not exist at runtime.  As such macros cannot be export‐
1286       ed at the bottom of a module like functions and other values.
1287
1288   import-macros load macros from a separate module
1289       (Since 0.4.0)
1290
1291       Loads a module at compile-time and binds its functions as local macros.
1292
1293       A macro module exports any number of functions which take code forms as
1294       arguments at compile time and emit lists which are fed  back  into  the
1295       compiler as code.  The module calling import-macros gets whatever func‐
1296       tions have been exported to use as macros.  For  instance,  here  is  a
1297       macro module which implements when2 in terms of if and do:
1298
1299              (fn when2 [condition body1 ...]
1300                (assert body1 "expected body")
1301                `(if ,condition
1302                   (do ,body1 ,...)))
1303
1304              {:when2 when2}
1305
1306       For  a  full  explanation  of  how this works see the macro guide.  All
1307       forms in Fennel are normal tables you can use table.insert, ipairs, de‐
1308       structuring, etc on.  The backtick on the third line creates a template
1309       list for the code emitted by the macro, and the comma  serves  as  "un‐
1310       quote"  which  splices  values into the template.  (Changed in 0.3.0: @
1311       was used instead of , before.)
1312
1313       Assuming the code above is in the file "my-macros.fnl"  then  it  turns
1314       this input:
1315
1316              (import-macros {: when2} :my-macros)
1317
1318              (when2 (= 3 (+ 2 a))
1319                (print "yes")
1320                (finish-calculation))
1321
1322       and  transforms it into this code at compile time by splicing the argu‐
1323       ments into the backtick template:
1324
1325              (if (= 3 (+ 2 a))
1326                (do
1327                  (print "yes")
1328                  (finish-calculation)))
1329
1330       The import-macros macro can  take  any  number  of  binding/module-name
1331       pairs.   It  can  also  bind  the  entire macro module to a single name
1332       rather than destructuring it.  In this case you can use a dot  to  call
1333       the individual macros inside the module:
1334
1335              (import-macros mine :my-macros)
1336
1337              (mine.when2 (= 3 (+ 2 a))
1338                (print "yes")
1339                (finish-calculation))
1340
1341       Note  that  all  macro  code runs at compile time, which happens before
1342       runtime.  Locals which are in scope at runtime are not  visible  during
1343       compile-time.  So this code will not work:
1344
1345              (local (module-name file-name) ...)
1346              (import-macros mymacros (.. module-name ".macros"))
1347
1348       However, this code will work, provided the module in question exists:
1349
1350              (import-macros mymacros (.. ... ".macros"))
1351
1352       See "Compiler API" below for details about additional functions visible
1353       inside compiler scope which macros run in.
1354
1355   Macro module searching
1356       By default, Fennel will search for macro modules similarly  to  how  it
1357       searches  for  normal  runtime modules: by walking thru entries on fen‐
1358       nel.macro-path and checking the filesystem for  matches.   However,  in
1359       some cases this might not be suitable, for instance if your Fennel pro‐
1360       gram is packaged in some kind of archive file and the  modules  do  not
1361       exist as distinct files on disk.
1362
1363       To support this case you can add your own searcher function to the fen‐
1364       nel.macro-searchers table.  For example, assuming find-in-archive is  a
1365       function which can look up strings from the archive given a path:
1366
1367              (local fennel (require :fennel))
1368
1369              (fn my-searcher [module-name]
1370                (let [filename (.. "src/" module-name ".fnl")]
1371                  (match (find-in-archive filename)
1372                    code (values (partial fennel.eval code {:env :_COMPILER})
1373                                 filename))))
1374
1375              (table.insert fennel.macro-searchers my-searcher)
1376
1377       The  searcher function should take a module name as a string and return
1378       two values if it can find the macro module:  a  loader  function  which
1379       will return the macro table when called, and an optional filename.  The
1380       loader function will receive the module name and the filename as  argu‐
1381       ments.
1382
1383   macros define several macros
1384       (Since 0.3.0)
1385
1386       Defines a table of macros.  Note that inside the macro definitions, you
1387       cannot access variables and bindings from the  surrounding  code.   The
1388       macros  are  essentially  compiled  in  their own compiler environment.
1389       Again, see the "Compiler API" section for more details about the  func‐
1390       tions available here.
1391
1392              (macros {:my-max (fn [x y]
1393                                 `(let [x# ,x y# ,y]
1394                                    (if (< x# y#) y# x#)))})
1395
1396              (print (my-max 10 20))
1397              (print (my-max 20 10))
1398              (print (my-max 20 20))
1399
1400   macro define a single macro
1401              (macro my-max [x y]
1402                `(let [x# ,x y# ,y]
1403                   (if (< x# y#) y# x#)))
1404
1405       If you are only defining a single macro, this is equivalent to the pre‐
1406       vious example.  The syntax mimics fn.
1407
1408   macrodebug print the expansion of a macro
1409              (macrodebug (-> abc
1410                              (+ 99)
1411                              (< 0)
1412                              (when (os.exit))))
1413              ; -> (if (< (+ abc 99) 0) (do (os.exit)))
1414
1415       Call the macrodebug macro with a form and  it  will  repeatedly  expand
1416       top-level  macros  in that form and print out the resulting form.  Note
1417       that the resulting form will usually not be sensibly indented,  so  you
1418       might need to copy it and reformat it into something more readable.
1419
1420       Note that this prints at compile-time since macrodebug is a macro.
1421
1422   Macro gotchas
1423       It's  easy  to  make macros which accidentally evaluate their arguments
1424       more than once.  This is fine if they are passed literal values, but if
1425       they are passed a form which has side-effects, the result will be unex‐
1426       pected:
1427
1428              (var v 1)
1429              (macros {:my-max (fn [x y]
1430                                 `(if (< ,x ,y) ,y ,x))})
1431
1432              (fn f [] (set v (+ v 1)) v)
1433
1434              (print (my-max (f) 2)) ; -> 3 since (f) is called twice in the macro body above
1435
1436       (Since  0.3.0)  In  order  to   prevent   accidental   symbol   capture
1437       (https://gist.github.com/nimaai/2f98cc421c9a51930e16#variable-capture),
1438       you may not bind a bare symbol inside a backtick as an identifier.  Ap‐
1439       pending  a  #  on the end of the identifier name as above invokes "auto
1440       gensym" which guarantees the local name is unique.
1441
1442              (macros {:my-max (fn [x y]
1443                                 `(let [x2 ,x y2 ,y]
1444                                    (if (< x2 y2) y2 x2)))})
1445
1446              (print (my-max 10 20))
1447              ; Compile error in 'x2' unknown:?: macro tried to bind x2 without gensym; try x2# instead
1448
1449       macros is useful for one-off, quick macros, or even some  more  compli‐
1450       cated  macros,  but be careful.  It may be tempting to try and use some
1451       function you have previously defined, but if you need such functionali‐
1452       ty, you should probably use import-macros.
1453
1454       For  example,  this will not compile in strict mode!  Even when it does
1455       allow the macro to be called, it will fail trying to call a global  my-
1456       fn when the code is run:
1457
1458              (fn my-fn [] (print "hi!"))
1459
1460              (macros {:my-max (fn [x y]
1461                                 (my-fn)
1462                                 `(let [x# ,x y# ,y]
1463                                    (if (< x# y#) y# x#)))})
1464              ; Compile error in 'my-max': attempt to call global '__fnl_global__my_2dfn' (a nil value)
1465
1466   eval-compiler
1467       Evaluate  a  block  of code during compile-time with access to compiler
1468       scope.  This gives you a superset of the  features  you  can  get  with
1469       macros, but you should use macros if you can.
1470
1471       Example:
1472
1473              (eval-compiler
1474                (each [name (pairs _G)]
1475                  (print name)))
1476
1477       This prints all the functions available in compiler scope.
1478
1479   Compiler Environment
1480       Inside eval-compiler, macros, or macro blocks, as well as import-macros
1481       modules, the functions listed below are visible to your code.
1482
1483list - return a list, which is a special kind of table used for code.
1484
1485sym - turn a string into a symbol.
1486
1487gensym - generates a unique symbol for use in macros, accepts an  op‐
1488         tional prefix string.
1489
1490list? - is the argument a list?  Returns the argument or false.
1491
1492sym? - is the argument a symbol?  Returns the argument or false.
1493
1494table?  -  is the argument a non-list table?  Returns the argument or
1495         false.
1496
1497sequence? - is the argument a non-list sequential table (created with
1498         [], as opposed to {})?  Returns the argument or false.
1499
1500varg?  -  is  this  a ... symbol which indicates var args?  Returns a
1501         special table describing the type or false.
1502
1503multi-sym? - a multi-sym is a dotted symbol which refers to a table's
1504         field.  Returns a table containing each separate symbol, or false.
1505
1506comment?  -  is  the  argument a comment?  Comments are only included
1507         when opts.comments is truthy.
1508
1509view - fennel.view table serializer.
1510
1511get-scope - return the scope table for the current macro call site.
1512
1513assert-compile - works like assert but takes  a  list/symbol  as  its
1514         third argument in order to provide pinpointed error messages.
1515
1516       These functions can be used from within macros only, not from any eval-
1517       compiler call:
1518
1519in-scope? - does the symbol refer to an in-scope local?  Returns  the
1520         symbol or nil.
1521
1522macroexpand  -  performs macroexpansion on its argument form; returns
1523         an AST.
1524
1525       Note that lists are compile-time concepts that don't exist at  runtime;
1526       they  are  implemented as tables which have a special metatable to dis‐
1527       tinguish them from regular tables defined with square or  curly  brack‐
1528       ets.   Similarly  symbols are tables with a string entry for their name
1529       and a marker metatable.  You can use tostring to get the name of a sym‐
1530       bol.
1531
1532       As  of  1.0.0  the  compiler will not allow access to the outside world
1533       (os, io, etc) from macros.  The one exception is print which is includ‐
1534       ed  for debugging purposes.  You can disable this by providing the com‐
1535       mand-line argument --no-compiler-sandbox or by  passing  {:compiler-env
1536       _G}  in  the  options table when using the compiler API to get full ac‐
1537       cess.
1538
1539       Please note that the sandbox is not suitable to be used as a robust se‐
1540       curity mechanism.  It has not been audited and should not be relied up‐
1541       on to protect you from running untrusted code.
1542
1543       Note that other internals of the compiler exposed in compiler scope but
1544       not listed above are subject to change.
1545

lua ESCAPE HATCH

1547       There  are  some  cases when you need to emit Lua output from Fennel in
1548       ways that don't match Fennel's semantics.  For  instance,  if  you  are
1549       porting  an algorithm from Lua that uses early returns, you may want to
1550       do the port as literally as possible first, and then come  back  to  it
1551       later to make it idiomatic.  You can use the lua special form to accom‐
1552       plish this:
1553
1554              (fn find [tbl pred]
1555                (each [key val (pairs tbl)]
1556                  (when (pred val)
1557                    (lua "return key"))))
1558
1559       Lua code inside the string can refer to locals which are in scope; how‐
1560       ever note that it must refer to the names after mangling has been done,
1561       because the identifiers must be valid Lua.  The  Fennel  compiler  will
1562       change  foo-bar  to  foo_bar  in  the  Lua output in order for it to be
1563       valid, as well as other transformations.  When in  doubt,  inspect  the
1564       compiler  output  to see what it looks like.  For example the following
1565       Fennel code:
1566
1567              (local foo-bar 3)
1568              (let [foo-bar :hello]
1569                (lua "print(foo_bar0 .. \" world\")"))
1570
1571       will produce this Lua code:
1572
1573              local foo_bar = 3
1574              local foo_bar0 = "hello"
1575              print(foo_bar0 .. " world")
1576              return nil
1577
1578       Normally in these cases you would want to emit a  statement,  in  which
1579       case  you  would  pass a string of Lua code as the first argument.  But
1580       you can also use it to emit an expression if you pass in  a  string  as
1581       the second argument.
1582
1583       Note that this should only be used in exceptional circumstances, and if
1584       you are able to avoid it, you should.
1585

DEPRECATED FORMS

1587   require-macros load macros with less flexibility
1588       (Since 0.1.0, deprecated in 0.4.0)
1589
1590       The require-macros form is like import-macros, except  it  imports  all
1591       macros  without  making  it clear what new identifiers are brought into
1592       scope.  It is strongly recommended to use import-macros instead.
1593
1594   pick-args create a function of fixed arity
1595       (Since 0.4.0, deprecated 0.10.0)
1596
1597       Like pick-values, but takes an integer n and a function/operator f, and
1598       creates a new function that applies exactly n arguments to f.
1599
1600   global set global variable
1601       (Deprecated in 1.1.0)
1602
1603       Sets  a global variable to a new value.  Note that there is no distinc‐
1604       tion between introducing a new global and changing the value of an  ex‐
1605       isting one.  This supports destructuring and multiple-value binding.
1606
1607       Example:
1608
1609              (global prettyprint (fn [x] (print (fennel.view x))))
1610
1611       Using  global  adds  the  identifier in question to the list of allowed
1612       globals so that referring to it later on will not cause a compiler  er‐
1613       ror.   However, globals are also available in the _G table, and access‐
1614       ing them that way instead is recommended for clarity.
1615

AUTHORS

1617       Fennel Maintainers.
1618
1619
1620
1621fennel 1.3.1                      2023-07-05               fennel-reference(5)
Impressum