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

Add support for static anonymous functions #988

Draft
wants to merge 4 commits into
base: draft-v9
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion standard/conversions.md
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,7 @@ Anonymous functions may influence overload resolution, and participate in type i

### 10.7.2 Evaluation of anonymous function conversions to delegate types

Conversion of an anonymous function to a delegate type produces a delegate instance that references the anonymous function and the (possibly empty) set of captured outer variables that are active at the time of the evaluation. When the delegate is invoked, the body of the anonymous function is executed. The code in the body is executed using the set of captured outer variables referenced by the delegate. A *delegate_creation_expression* ([§12.8.16.6](expressions.md#128166-delegate-creation-expressions)) can be used as an alternate syntax for converting an anonymous method to a delegate type.
Conversion of an anonymous function to a delegate type produces a delegate instance that references the anonymous function and, for non-`static` anonymous functions, the (possibly empty) set of captured outer variables that are active at the time of the evaluation. When the delegate is invoked, the body of the anonymous function is executed. The code in the body is executed using the set of captured outer variables referenced by the delegate. A *delegate_creation_expression* ([§12.8.16.6](expressions.md#128166-delegate-creation-expressions)) can be used as an alternate syntax for converting an anonymous method to a delegate type.

The invocation list of a delegate produced from an anonymous function contains a single entry. The exact target object and target method of the delegate are unspecified. In particular, it is unspecified whether the target object of the delegate is `null`, the `this` value of the enclosing function member, or some other object.

Expand Down
37 changes: 26 additions & 11 deletions standard/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -4853,11 +4853,16 @@ An ***anonymous function*** is an expression that represents an “in-line” me

```ANTLR
lambda_expression
: 'async'? anonymous_function_signature '=>' anonymous_function_body
: anonymous_function_modifier? anonymous_function_signature '=>' anonymous_function_body
;

anonymous_method_expression
: 'async'? 'delegate' explicit_anonymous_function_signature? block
: anonymous_function_modifier? 'delegate' explicit_anonymous_function_signature? block
;

anonymous_function_modifier
: 'async' 'static'?
| 'static' 'async'?
;

anonymous_function_signature
Expand Down Expand Up @@ -4906,6 +4911,12 @@ anonymous_function_body
;
```

If the modifier `static` is present, the anonymous function cannot capture state from the enclosing scope.

A non-`static` local function or non-`static` anonymous function can capture state from an enclosing `static` anonymous function, but cannot capture state outside the enclosing static anonymous function.

Removing the `static` modifier from an anonymous function in a valid program does not change the meaning of the program.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should static ensure that all delegate instances converted from the same anonymous function shall compare equal? (That would not require any caching of delegate instances.)

using System;
using System.Diagnostics;

class C {
    Action G() {
        return static () => {};
    }
    void M() {
        Debug.Assert(G() == G());
    }
}

I think static should not guarantee this equality. IIRC Roslyn generates an instance method even for a static anonymous function because it is more efficient for the calling convention. Then the delegate will refer to some instance, and will compare unequal if it refers to a different instance. Requiring such an implementation to ensure that the same instance is used every time might cost additional interlocked operations for thread safety.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a note about this in the specification of delegate equality would be useful though.


When recognising an *anonymous_function_body* if both the *null_conditional_invocation_expression* and *expression* alternatives are applicable then the former shall be chosen.

<!-- markdownlint-disable MD028 -->
Expand Down Expand Up @@ -4955,11 +4966,11 @@ A *block* body of an anonymous function is always reachable ([§13.2](statements
> x => x + 1 // Implicitly typed, expression body
> x => { return x + 1; } // Implicitly typed, block body
> (int x) => x + 1 // Explicitly typed, expression body
> (int x) => { return x + 1; } // Explicitly typed, block body
> static (int x) => { return x + 1; } // Explicitly typed, block body
> (x, y) => x * y // Multiple parameters
> () => Console.WriteLine() // No parameters
> async (t1,t2) => await t1 + await t2 // Async
> delegate (int x) { return x + 1; } // Anonymous method expression
> static delegate (int x) { return x + 1; } // Anonymous method expression
> delegate { return 1 + 1; } // Parameter list omitted
> ```
>
Expand Down Expand Up @@ -4989,8 +5000,10 @@ The body (*expression* or *block*) of an anonymous function is subject to the fo
- If the anonymous function includes a signature, the parameters specified in the signature are available in the body. If the anonymous function has no signature it can be converted to a delegate type or expression type having parameters ([§10.7](conversions.md#107-anonymous-function-conversions)), but the parameters cannot be accessed in the body.
- Except for `in`, `out`, or `ref` parameters specified in the signature (if any) of the nearest enclosing anonymous function, it is a compile-time error for the body to access an `in`, `out`, or `ref` parameter.
- Except for parameters specified in the signature (if any) of the nearest enclosing anonymous function, it is a compile-time error for the body to access a parameter of a `ref struct` type.
- When the type of `this` is a struct type, it is a compile-time error for the body to access `this`. This is true whether the access is explicit (as in `this.x`) or implicit (as in `x` where `x` is an instance member of the struct). This rule simply prohibits such access and does not affect whether member lookup results in a member of the struct.
- The body has access to the outer variables ([§12.19.6](expressions.md#12196-outer-variables)) of the anonymous function. Access of an outer variable will reference the instance of the variable that is active at the time the *lambda_expression* or *anonymous_method_expression* is evaluated ([§12.19.7](expressions.md#12197-evaluation-of-anonymous-function-expressions)).
- If the modifier `static` is present, it is a compile-time error for the body to access `this` or `base`.
- If the modifier `static` is absent, when the type of `this` is a struct type, it is a compile-time error for the body to access `this`. This is true whether the access is explicit (as in `this.x`) or implicit (as in `x` where `x` is an instance member of the struct). This rule simply prohibits such access and does not affect whether member lookup results in a member of the struct.
- If the modifier `static` is absent, the body has access to the outer variables ([§12.19.6](expressions.md#12196-outer-variables)) of the anonymous function. Access of an outer variable will reference the instance of the variable that is active at the time the *lambda_expression* or *anonymous_method_expression* is evaluated ([§12.19.7](expressions.md#12197-evaluation-of-anonymous-function-expressions)).
- If the modifier `static` is present, the body may use outer variable names as operands to `nameof`.
- It is a compile-time error for the body to contain a `goto` statement, a `break` statement, or a `continue` statement whose target is outside the body or within the body of a contained anonymous function.
- A `return` statement in the body returns control from an invocation of the nearest enclosing anonymous function, not from the enclosing function member.

Expand Down Expand Up @@ -5075,9 +5088,11 @@ An anonymous function cannot be a receiver, argument, or operand of a dynamicall

Any local variable, value parameter, or parameter array whose scope includes the *lambda_expression* or *anonymous_method_expression* is called an ***outer variable*** of the anonymous function. In an instance function member of a class, the this value is considered a value parameter and is an outer variable of any anonymous function contained within the function member.

That said, if the modifier `static` is present, the anonymous function cannot capture state from the enclosing scope. As a result, locals, parameters, and `this` from the enclosing scope are not available to that anonymous function.

#### 12.19.6.2 Captured outer variables

When an outer variable is referenced by an anonymous function, the outer variable is said to have been ***captured*** by the anonymous function. Ordinarily, the lifetime of a local variable is limited to execution of the block or statement with which it is associated ([§9.2.9](variables.md#929-local-variables)). However, the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.
When an outer variable is referenced by a non-`static` anonymous function, the outer variable is said to have been ***captured*** by the anonymous function. Ordinarily, the lifetime of a local variable is limited to execution of the block or statement with which it is associated ([§9.2.9](variables.md#929-local-variables)). However, the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.

> *Example*: In the example
>
Expand Down Expand Up @@ -5114,7 +5129,7 @@ When an outer variable is referenced by an anonymous function, the outer variabl
>
> *end example*

When a local variable or a value parameter is captured by an anonymous function, the local variable or parameter is no longer considered to be a fixed variable ([§23.4](unsafe-code.md#234-fixed-and-moveable-variables)), but is instead considered to be a moveable variable. However, captured outer variables cannot be used in a `fixed` statement ([§23.7](unsafe-code.md#237-the-fixed-statement)), so the address of a captured outer variable cannot be taken.
When a local variable or a value parameter is captured by a non-`static` anonymous function, the local variable or parameter is no longer considered to be a fixed variable ([§23.4](unsafe-code.md#234-fixed-and-moveable-variables)), but is instead considered to be a moveable variable. However, captured outer variables cannot be used in a `fixed` statement ([§23.7](unsafe-code.md#237-the-fixed-statement)), so the address of a captured outer variable cannot be taken.

> *Note*: Unlike an uncaptured variable, a captured local variable can be simultaneously exposed to multiple threads of execution. *end note*

Expand Down Expand Up @@ -5153,7 +5168,7 @@ A local variable is considered to be ***instantiated*** when execution enters th
>
> *end example*

When not captured, there is no way to observe exactly how often a local variable is instantiated—because the lifetimes of the instantiations are disjoint, it is possible for each instantation to simply use the same storage location. However, when an anonymous function captures a local variable, the effects of instantiation become apparent.
When not captured, there is no way to observe exactly how often a local variable is instantiated—because the lifetimes of the instantiations are disjoint, it is possible for each instantiation to simply use the same storage location. However, when a non-`static` anonymous function captures a local variable, the effects of instantiation become apparent.

> *Example*: The example
>
Expand Down Expand Up @@ -5273,7 +5288,7 @@ If a for-loop declares an iteration variable, that variable itself is considered
>
> *end example*

It is possible for anonymous function delegates to share some captured variables yet have separate instances of others.
It is possible for non-`static` anonymous function delegates to share some captured variables yet have separate instances of others.

> *Example*: For example, if `F` is changed to
>
Expand Down Expand Up @@ -5302,7 +5317,7 @@ It is possible for anonymous function delegates to share some captured variables
>
> *end example*

Separate anonymous functions can capture the same instance of an outer variable.
Separate non-`static` anonymous functions can capture the same instance of an outer variable.

> *Example*: In the example:
>
Expand Down
2 changes: 1 addition & 1 deletion standard/unsafe-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ The `&` operator ([§23.6.5](unsafe-code.md#2365-the-address-of-operator)) permi

In precise terms, a fixed variable is one of the following:

- A variable resulting from a *simple_name* ([§12.8.4](expressions.md#1284-simple-names)) that refers to a local variable, value parameter, or parameter array, unless the variable is captured by an anonymous function ([§12.19.6.2](expressions.md#121962-captured-outer-variables)).
- A variable resulting from a *simple_name* ([§12.8.4](expressions.md#1284-simple-names)) that refers to a local variable, value parameter, or parameter array, unless the variable is captured by a non-`static` anonymous function ([§12.19.6.2](expressions.md#121962-captured-outer-variables)).
- A variable resulting from a *member_access* ([§12.8.7](expressions.md#1287-member-access)) of the form `V.I`, where `V` is a fixed variable of a *struct_type*.
- A variable resulting from a *pointer_indirection_expression* ([§23.6.2](unsafe-code.md#2362-pointer-indirection)) of the form `*P`, a *pointer_member_access* ([§23.6.3](unsafe-code.md#2363-pointer-member-access)) of the form `P->I`, or a *pointer_element_access* ([§23.6.4](unsafe-code.md#2364-pointer-element-access)) of the form `P[E]`.

Expand Down
4 changes: 2 additions & 2 deletions standard/variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ For the purpose of definite-assignment checking, an array element is considered

A parameter declared without an `in`, `out`, or `ref` modifier is a ***value parameter***.

A value parameter comes into existence upon invocation of the function member (method, instance constructor, accessor, or operator) or anonymous function to which the parameter belongs, and is initialized with the value of the argument given in the invocation. A value parameter normally ceases to exist when execution of the function body completes. However, if the value parameter is captured by an anonymous function ([§12.19.6.2](expressions.md#121962-captured-outer-variables)), its lifetime extends at least until the delegate or expression tree created from that anonymous function is eligible for garbage collection.
A value parameter comes into existence upon invocation of the function member (method, instance constructor, accessor, or operator) or anonymous function to which the parameter belongs, and is initialized with the value of the argument given in the invocation. A value parameter normally ceases to exist when execution of the function body completes. However, if the value parameter is captured by a non-`static` anonymous function ([§12.19.6.2](expressions.md#121962-captured-outer-variables)), its lifetime extends at least until the delegate or expression tree created from that anonymous function is eligible for garbage collection.

For the purpose of definite-assignment checking, a value parameter is considered initially assigned.

Expand Down Expand Up @@ -124,7 +124,7 @@ A ***local variable*** is declared by a *local_variable_declaration*, *declarati

A *local_variable_declaration* can occur in a *block*, a *for_statement*, a *switch_block*, or a *using_statement*. A *declaration_expression* can occur as an `out` *argument_value*, and as a *tuple_element* that is the target of a deconstructing assignment ([§12.21.2](expressions.md#12212-simple-assignment)).

The lifetime of a local variable is the portion of program execution during which storage is guaranteed to be reserved for it. This lifetime extends from entry into the scope with which it is associated, at least until execution of that scope ends in some way. (Entering an enclosed *block*, calling a method, or yielding a value from an iterator block suspends, but does not end, execution of the current scope.) If the local variable is captured by an anonymous function ([§12.19.6.2](expressions.md#121962-captured-outer-variables)), its lifetime extends at least until the delegate or expression tree created from the anonymous function, along with any other objects that come to reference the captured variable, are eligible for garbage collection. If the parent scope is entered recursively or iteratively, a new instance of the local variable is created each time, and its initializer, if any, is evaluated each time.
The lifetime of a local variable is the portion of program execution during which storage is guaranteed to be reserved for it. This lifetime extends from entry into the scope with which it is associated, at least until execution of that scope ends in some way. (Entering an enclosed *block*, calling a method, or yielding a value from an iterator block suspends, but does not end, execution of the current scope.) If the local variable is captured by a non-`static` anonymous function ([§12.19.6.2](expressions.md#121962-captured-outer-variables)), its lifetime extends at least until the delegate or expression tree created from the anonymous function, along with any other objects that come to reference the captured variable, are eligible for garbage collection. If the parent scope is entered recursively or iteratively, a new instance of the local variable is created each time, and its initializer, if any, is evaluated each time.

> *Note*: A local variable is instantiated each time its scope is entered. This behavior is visible to user code containing anonymous methods. *end note*
<!-- markdownlint-disable MD028 -->
Expand Down