ADD: syntaxic sugar for function declaration.

main
bog 2023-09-23 05:58:13 +02:00
parent 22131c2cf0
commit 5d975eafdf
5 changed files with 45 additions and 1 deletions

View File

@ -4,7 +4,10 @@ EXPR ::=
| ident | ident
| CALL | CALL
| LAMBDA | LAMBDA
| FUNDECL
CALL ::= opar EXPR EXPR* cpar CALL ::= opar EXPR EXPR* cpar
LAMBDA ::= opar rarrow opar PARAMS cpar BODY cpar LAMBDA ::= opar rarrow opar PARAMS cpar BODY cpar
PARAMS ::= ident* PARAMS ::= ident*
BODY ::= EXPR* BODY ::= EXPR*
FUNDECL ::=
| opar ident opar ident PARAMS cpar BODY cpar

3
examples/fundecl.fk Normal file
View File

@ -0,0 +1,3 @@
($ (f x y) (* x y))
(assert= 42 (f 6 7))

View File

@ -59,7 +59,12 @@ namespace fk
return consume(); return consume();
} }
if (type_all({NODE_OPAR, NODE_RARROW})) if (type_all({NODE_OPAR, NODE_IDENT, NODE_OPAR, NODE_IDENT})
&& m_tokens[m_cursor + 1]->repr() == "$")
{
return parse_fundecl();
}
else if (type_all({NODE_OPAR, NODE_RARROW}))
{ {
return parse_lambda(); return parse_lambda();
} }
@ -134,6 +139,31 @@ namespace fk
return node; return node;
} }
std::shared_ptr<Node> Parser::parse_fundecl()
{
consume(NODE_OPAR);
auto dollar = consume(NODE_IDENT);
consume(NODE_OPAR);
auto ident = consume(NODE_IDENT);
auto params = parse_params();
consume(NODE_CPAR);
auto body = parse_body();
consume(NODE_CPAR);
auto res = make_node(NODE_CALL);
res->add_child(dollar);
res->add_child(ident);
auto lambda = make_node(NODE_LAMBDA);
lambda->add_child(params);
lambda->add_child(body);
res->add_child(lambda);
return res;
}
std::shared_ptr<Node> Parser::make_node(NodeType type) std::shared_ptr<Node> Parser::make_node(NodeType type)
{ {
return std::make_shared<Node>(type, "", loc()); return std::make_shared<Node>(type, "", loc());

View File

@ -26,6 +26,7 @@ namespace fk
std::shared_ptr<Node> parse_lambda(); std::shared_ptr<Node> parse_lambda();
std::shared_ptr<Node> parse_params(); std::shared_ptr<Node> parse_params();
std::shared_ptr<Node> parse_body(); std::shared_ptr<Node> parse_body();
std::shared_ptr<Node> parse_fundecl();
std::shared_ptr<Node> make_node(NodeType type); std::shared_ptr<Node> make_node(NodeType type);
Loc loc() const; Loc loc() const;

View File

@ -47,3 +47,10 @@ TEST_CASE_METHOD(ParserTest, "Parser_lambda")
test_parse("MODULE(LAMBDA(PARAMS(IDENT[x],IDENT[y]),BODY(INT[7])))", test_parse("MODULE(LAMBDA(PARAMS(IDENT[x],IDENT[y]),BODY(INT[7])))",
" (-> (x y) 7) "); " (-> (x y) 7) ");
} }
TEST_CASE_METHOD(ParserTest, "Parser_fundecl")
{
test_parse("MODULE(CALL(IDENT[$],IDENT[f],"
"LAMBDA(PARAMS(IDENT[x]),BODY(INT[7]))))",
" ($ (f x) 7) ");
}