Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions ndc_parser/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,17 @@ impl Parser {
)
}

/// Whether the current tokens start a named function, as in `fn f(x)`
/// or `pure fn f(x)`, rather than an anonymous one, as in `fn(x)`.
fn at_named_function(&self) -> bool {
let mut tokens = self.tokens[self.current..].iter().map(|t| &t.token);
let mut token = tokens.next();
while token == Some(&Token::Pure) {
token = tokens.next();
}
token == Some(&Token::Fn) && matches!(tokens.next(), Some(Token::Identifier(_)))
}

fn peek_next_token(&self) -> Option<&Token> {
self.tokens.get(self.current + 1).map(|t| &t.token)
}
Expand Down Expand Up @@ -330,13 +341,15 @@ impl Parser {
} else if self
.match_token(&[Token::If, Token::While, Token::For, Token::LeftCurlyBracket])
.is_some()
|| self.at_named_function()
{
// A statement that starts with an `if`, a loop or a block ends
// at its closing brace, as in Rust: what follows starts the next
// statement, so `for x in xs { ... }` and then `[x]` on the next
// line is a list, not an index into the loop's value. Within an
// expression they still take an index or a call, as in
// `print(if c { [1] } else { [2] }[0])`.
// A statement that starts with an `if`, a loop, a block or a named
// function ends at its closing brace, as in Rust: what follows
// starts the next statement, so `for x in xs { ... }` and then
// `[x]` on the next line is a list, not an index into the loop's
// value, and `fn f(x) { ... }` and then `(1, 2).print` is not a
// call of `f`. Within an expression they still take an index or a
// call, as in `print(if c { [1] } else { [2] }[0])`.
self.primary()?
} else {
self.expression()?
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// A statement that starts with a named function ends at its closing brace, so
// a tuple or a list on the next line starts a statement of its own instead of
// calling or indexing the function. An anonymous function can still be called
// where it's written.
// expect-output: (1,2)
// expect-output: [3,4]
// expect-output: 6
fn f(x) { x + 1 }
(1, 2).print;
pure fn g(x) { x * 2 }
[3, 4].print;
fn(x) { x + 1 }(5).print;
Loading