Skip to content

Commit a503a26

Browse files
committed
Allow named function expressions
Necessary sometimes. Half of #21.
1 parent 8c0b3ee commit a503a26

File tree

3 files changed

+39
-4
lines changed

3 files changed

+39
-4
lines changed

doc/basics-reference.markdown

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,20 @@ macro compiles to a return-statement.
429429
return 5 * (a * b);
430430
};
431431

432+
433+
You can also give a name to a function expression as the optional first
434+
argument, if you so wish.
435+
436+
<!-- !test in named function expression -->
437+
438+
(var f (function tea () (return "T")))
439+
440+
<!-- !test out named function expression -->
441+
442+
var f = function tea() {
443+
return 'T';
444+
};
445+
432446
### Loops
433447

434448
While-loops (with the `while` macro) take the first argument to be the loop

src/built-in-macros.ls

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -298,11 +298,28 @@ contents =
298298
throw Error "dot called with no arguments"
299299

300300

301-
\function : ({compile, compile-many}:env, params, ...body) ->
301+
\function : ({compile, compile-many}:env, ...args) ->
302+
303+
# The first optional atom argument gives the id that should be attached to
304+
# the function expression. The next argument is the function's argument
305+
# list. All further arguments are statements for the body.
306+
307+
var id, params
308+
309+
arg1 = args.shift!
310+
311+
if arg1 instanceof atom
312+
id := type : \Identifier name : arg1.text!
313+
params := args.shift! .contents!map compile
314+
else
315+
# Let's assume it's a list then
316+
id := null
317+
params := arg1.contents!map compile
318+
302319
type : \FunctionExpression
303-
id : null
304-
params : params.contents!map compile
305-
body : optionally-implicit-block-statement env, body
320+
id : id
321+
params : params
322+
body : optionally-implicit-block-statement env, args
306323

307324
\new : ({compile}, ...args) ->
308325
[ newTarget, ...newArgs ] = args

test.ls

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,10 @@ test "function expression" ->
166166
esl "(function (x) (return (+ x 1)))"
167167
..`@equals` "(function (x) {\n return x + 1;\n});"
168168

169+
test "function expression with name" ->
170+
esl "(function f (x) (return (+ x 1)))"
171+
..`@equals` "(function f(x) {\n return x + 1;\n});"
172+
169173
test "function with no arguments" ->
170174
esl "(function () (return 1))"
171175
..`@equals` "(function () {\n return 1;\n});"

0 commit comments

Comments
 (0)