Skip to content

Commit 08847a5

Browse files
committed
Синтаксический сахар (= вместо return) для коротких функций
1 parent 951d6c9 commit 08847a5

File tree

2 files changed

+18
-8
lines changed

2 files changed

+18
-8
lines changed

program.own

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,18 +64,18 @@ print "\n\n"
6464
array = newarray(2, 2, 2, 2)
6565
print array
6666

67-
add = def(a,b) return a+b
68-
sub = def(a,b) return a-b
69-
mul = def(a,b) return a*b
70-
div = def(a,b) return a/b
71-
cube = def(x) return x*mul(x, x)
67+
add = def(a,b) = a+b
68+
sub = def(a,b) = a-b
69+
mul = def(a,b) = a*b
70+
div = def(a,b) = a/b
71+
cube = def(x) = x*mul(x, x)
7272
print "\n\n"
7373
print mul(8, 5)
7474
print "\n"
7575
print cube(2)
7676

7777
functions = [add, sub, mul, div]
78-
def function(f, a, b) return f(a, b)
78+
def function(f, a, b) = f(a, b)
7979
for i = 0, i < 4, i = i + 1 {
8080
print "\n"
8181
print functions[i]

src/com/annimon/ownlang/parser/Parser.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,10 @@ private FunctionDefineStatement functionDefine() {
141141
argNames.add(consume(TokenType.WORD).getText());
142142
match(TokenType.COMMA);
143143
}
144+
if (lookMatch(0, TokenType.EQ)) {
145+
match(TokenType.EQ);
146+
return new FunctionDefineStatement(name, argNames, new ReturnStatement(expression()));
147+
}
144148
final Statement body = statementOrBlock();
145149
return new FunctionDefineStatement(name, argNames, body);
146150
}
@@ -411,8 +415,14 @@ private Expression primary() {
411415
argNames.add(consume(TokenType.WORD).getText());
412416
match(TokenType.COMMA);
413417
}
414-
final Statement body = statementOrBlock();
415-
return new ValueExpression(new UserDefinedFunction(argNames, body));
418+
Statement statement;
419+
if (lookMatch(0, TokenType.EQ)) {
420+
match(TokenType.EQ);
421+
statement = new ReturnStatement(expression());
422+
} else {
423+
statement = statementOrBlock();
424+
}
425+
return new ValueExpression(new UserDefinedFunction(argNames, statement));
416426
}
417427
if (match(TokenType.LPAREN)) {
418428
Expression result = expression();

0 commit comments

Comments
 (0)