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

Make toDelegate safe for function pointers #8769

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
28 changes: 23 additions & 5 deletions std/functional.d
Original file line number Diff line number Diff line change
Expand Up @@ -1706,7 +1706,6 @@ private struct DelegateFaker(F)
*
* BUGS:
* $(UL
* $(LI Does not work with `@safe` functions.)
* $(LI Ignores C-style / D-style variadic arguments.)
* )
*/
Expand All @@ -1717,14 +1716,33 @@ if (isCallable!(F))
{
return fp;
}
else static if (is(F Func == Func*) && is(Func == function) && is(Func Params == __parameters))
{
// https://issues.dlang.org/show_bug.cgi?id=24007 - cannot specify linkage on function literal:
//alias dg = delegate(Params params) const => F.init(params);
//typeof(dg) result;
// Workaround:
struct S
{
mixin("extern(", __traits(getLinkage, fp), ") auto ref dg(Params params) const => F.init(params);");
}
typeof(&S().dg) result; // inlining `dg` infers attributes incorrectly

() @trusted
{
// assigning funcptr is @system, but it’s safe here because `fp` needs no context
result.funcptr = cast(typeof(result.funcptr)) fp;
}();
return result;
}
else static if (is(typeof(&F.opCall) == delegate)
|| (is(typeof(&F.opCall) V : V*) && is(V == function)))
{
return toDelegate(&fp.opCall);
}
else
{
alias DelType = typeof(&(new DelegateFaker!(F)).doIt);
alias DelType = typeof(&(new DelegateFaker!F).doIt);

static struct DelegateFields {
union {
Expand All @@ -1745,7 +1763,7 @@ if (isCallable!(F))

df.contextPtr = cast(void*) fp;

DelegateFaker!(F) dummy;
DelegateFaker!F dummy;
auto dummyDel = &dummy.doIt;
df.funcPtr = dummyDel.funcptr;

Expand All @@ -1754,7 +1772,7 @@ if (isCallable!(F))
}

///
@system unittest
@safe unittest
{
static int inc(ref uint num) {
num++;
Expand All @@ -1767,7 +1785,7 @@ if (isCallable!(F))
assert(myNum == 1);
}

@system unittest // not @safe due to toDelegate
@system unittest
{
static int inc(ref uint num) {
num++;
Expand Down