Skip to content

Commit f29fdf4

Browse files
committed
Add documentation about function literal context and parameter type inference.
1 parent be79c1a commit f29fdf4

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

expression.dd

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1381,13 +1381,13 @@ $(GNAME Lambda):
13811381
The first form is equivalent to:
13821382
)
13831383
---
1384-
delegate ( $(IDENTIFIER) ) { return $(I AssignExpression); }
1384+
( $(IDENTIFIER) ) { return $(I AssignExpression); }
13851385
---
13861386

13871387
$(P And the second:)
13881388

13891389
---
1390-
delegate $(I ParameterAttributes) { return $(I AssignExpression); }
1390+
$(I ParameterAttributes) { return $(I AssignExpression); }
13911391
---
13921392

13931393
Example usage:
@@ -1431,7 +1431,8 @@ $(V2 $(GLINK2 declaration, Parameters) $(GLINK2 declaration, FunctionAttrib
14311431
The type of a function literal is pointer to function or
14321432
pointer to delegate.
14331433
If the keywords $(B function) or $(B delegate) are omitted,
1434-
it defaults to being a delegate.)
1434+
it is inferred from whether $(I FunctionBody) is actually
1435+
accessing to the outer context.)
14351436

14361437
$(P For example:)
14371438

@@ -1480,16 +1481,36 @@ void test() {
14801481
}
14811482
-------------
14821483

1483-
$(P and the following where the return type $(B int) is
1484-
inferred:)
1484+
$(P and the following where the return type $(B int) and
1485+
$(B function)/$(B delegate) are inferred:)
14851486

14861487
-------------
14871488
int abc(int delegate(long i));
1489+
int def(int function(long s));
14881490

14891491
void test() {
14901492
int b = 3;
14911493

1492-
abc( $(B (long c) { return 6 + b; }) );
1494+
abc( $(B (long c) { return 6 + b; }) ); // inferred to $(B delegate)
1495+
def( $(B (long c) { return c * 2; }) ); // inferred to $(B function)
1496+
//def( $(B (long c) { return c * b; }) ); // error!
1497+
// Because the FunctionBody accesses b, then the function literal type
1498+
// is inferred to delegate. But def cannot receive delegate.
1499+
}
1500+
-------------
1501+
1502+
If the type of a function literal can be uniquely determined from its context,
1503+
the parameter type inference is possible.
1504+
1505+
-------------
1506+
void foo(int function(int) fp);
1507+
1508+
void test() {
1509+
int function(int) fp = (n) { return n * 2; };
1510+
// The type of parameter n is inferred to $(B int).
1511+
1512+
foo((n) { return n * 2; });
1513+
// The type of parameter n is inferred to $(B int).
14931514
}
14941515
-------------
14951516

0 commit comments

Comments
 (0)