Skip to content

Commit 12be92d

Browse files
Parse anonymous function with no clauses (#78)
1 parent d301895 commit 12be92d

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

docs/parser.md

+23
Original file line numberDiff line numberDiff line change
@@ -259,3 +259,26 @@ Resolving some of these conflicts (for instance special keywords like `{}` or `%
259259
requires the use of external scanner. Given the complexities this approach
260260
brings to the grammar, and consequently the parser, we stick to the simpler
261261
approach.
262+
263+
### Ref 8. Empty anonymous function
264+
265+
As opposed to the Elixir parser, we successfully parse anonymous functions with
266+
no stab clauses, so this is valid:
267+
268+
```
269+
x = fn
270+
271+
end
272+
```
273+
274+
This code may appear if an editor extension automatically inserts `end` after
275+
`fn`. We want it to parse as anonymous function node, so that functionality such
276+
as indentation works as expected.
277+
278+
If we require at least one stab clause, the above would be parsed with an error,
279+
where `fn` and `end` are both identifiers. That is not useful. Note that both
280+
`fn` and `end` are reserved keywords, so there is no case where they would
281+
actually be identifiers, hence no ambiguity.
282+
283+
Ideally, this would parse it as an anonymous function node with an error, however
284+
that does not seem straightforward to achieve.

grammar.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -829,7 +829,8 @@ module.exports = grammar({
829829
seq(
830830
"fn",
831831
optional($._terminator),
832-
sep1($.stab_clause, $._terminator),
832+
// See Ref 8. in the docs
833+
optional(sep1($.stab_clause, $._terminator)),
833834
"end"
834835
),
835836

test/corpus/expression/anonymous_function.txt

+15
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,21 @@ end
178178
(body
179179
(atom)))))
180180

181+
=====================================
182+
no clauses
183+
=====================================
184+
185+
fn
186+
end
187+
188+
fn end
189+
190+
---
191+
192+
(source
193+
(anonymous_function)
194+
(anonymous_function))
195+
181196
=====================================
182197
with guard / no arguments
183198
=====================================

0 commit comments

Comments
 (0)