Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow shortened method syntax for constructors #17079

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
15 changes: 15 additions & 0 deletions changelog/dmd.shortened-method-constructor.dd
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Shortened method syntax can now be used in constructors

This used to raise an error "cannot return expression from constructor", but it's now supported:

---
struct Number
{
int x;

this(int x) => this.x = x;
this(float x) => this(cast(int) x);
}
---

Postblits and destructors already supported shortened method syntax because they return `void`.
5 changes: 4 additions & 1 deletion compiler/src/dmd/parse.d
Original file line number Diff line number Diff line change
Expand Up @@ -5252,7 +5252,10 @@ class Parser(AST, Lexer = dmd.lexer.Lexer) : Lexer
error("missing `do { ... }` after `in` or `out`");
const returnloc = token.loc;
nextToken();
f.fbody = new AST.ReturnStatement(returnloc, parseExpression());
if (f.isCtorDeclaration)
f.fbody = new AST.ExpStatement(returnloc, parseExpression());
else
f.fbody = new AST.ReturnStatement(returnloc, parseExpression());
f.endloc = token.loc;
check(TOK.semicolon);
break;
Expand Down
13 changes: 13 additions & 0 deletions compiler/test/compilable/shortened_methods.d
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ class A {

// or normal method defintions
bool isNull() => this is null;

this() {}
this(int x) => _x = x;
this(float y) => this(cast(int) y);
}

class B : A{
Expand All @@ -36,3 +40,12 @@ void func() {
// Issue 24088 - https://issues.dlang.org/show_bug.cgi?id=24088
S!int f() => S!int();
}

struct T
{
void inc() {}
this(this) => inc();

void free() {}
~this() => free();
}
Loading