diff --git a/standard/README.md b/standard/README.md index df0205ee7..061045f93 100644 --- a/standard/README.md +++ b/standard/README.md @@ -727,7 +727,9 @@ - [§16.6.5](structs.md#1665-default-values) Default values - [§16.6.6](structs.md#1666-boxing-and-unboxing) Boxing and unboxing - [§16.6.7](structs.md#1667-meaning-of-this) Meaning of this - - [§16.6.8](structs.md#1668-field-initializers) Field initializers + - [§fields](structs.md#fields-fields) Fields + - [§field-initializers](structs.md#field-initializers-field-initializers) Field initializers + - [§Ref-Fields](structs.md#ref-fields-ref-fields) Ref fields - [§16.6.9](structs.md#1669-constructors) Constructors - [§16.6.10](structs.md#16610-static-constructors) Static constructors - [§16.6.11](structs.md#16611-properties) Properties diff --git a/standard/attributes.md b/standard/attributes.md index 21983344c..312c896ef 100644 --- a/standard/attributes.md +++ b/standard/attributes.md @@ -504,6 +504,7 @@ A number of attributes affect the language in some way. These attributes include - `System.Runtime.CompilerServices.EnumeratorCancellationAttribute` ([§23.5.8](attributes.md#2358-the-enumeratorcancellation-attribute)), which is used to specify parameter for the cancellation token in an asynchronous iterator. - `System.Runtime.CompilerServices.ModuleInitializerAttribute` ([§23.5.9](attributes.md#2359-the-moduleinitializer-attribute)), which is used to mark a method as a module initializer. - `System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute` and `System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute`, which are used to declare a custom interpolated string expression handler ([§23.5.9.1](attributes.md#23591-custom-interpolated-string-expression-handlers)) and to call one of its constructors, respectively. +- System.Diagnostics.CodeAnalysis.UnscopedRefAttribute (§UnscopedRefAttribute), which allows an otherwise implicitly scoped ref to be treated as not being scoped. The Nullable static analysis attributes ([§23.5.7](attributes.md#2357-code-analysis-attributes)) can improve the correctness of warnings generated for nullabilities and null states ([§8.9.5](types.md#895-nullabilities-and-null-states)). @@ -1058,19 +1059,19 @@ The attributes in this subclause are used to provide additional information to s The code-analysis attributes are declared in namespace `System.Diagnostics.CodeAnalysis`. -**Attribute** | **Meaning** ------------------- | ------------------ -`AllowNullAttribute` ([§23.5.7.2](attributes.md#23572-the-allownull-attribute)) | A non-nullable argument may be null. -`DisallowNullAttribute` ([§23.5.7.3](attributes.md#23573-the-disallownull-attribute)) | A nullable argument should never be null. -`MaybeNullAttribute` ([§23.5.7.6](attributes.md#23576-the-maybenull-attribute)) | A non-nullable return value may be null. -`NotNullAttribute` ([§23.5.7.10](attributes.md#235710-the-notnull-attribute)) | A nullable return value will never be null. -`MaybeNullWhenAttribute` ([§23.5.7.7](attributes.md#23577-the-maybenullwhen-attribute)) | A non-nullable argument may be null when the method returns the specified `bool` value. -`NotNullWhenAttribute` ([§23.5.7.12](attributes.md#235712-the-notnullwhen-attribute)) | A nullable argument will not be null when the method returns the specified `bool` value. -`NotNullIfNotNullAttribute` ([§23.5.7.11](attributes.md#235711-the-notnullifnotnull-attribute)) | A return value is not null if the argument for the specified parameter is not null. -`MemberNotNullAttribute` ([§23.5.7.8](attributes.md#23578-the-membernotnull-attribute)) | The listed member will not be null when the method returns. -`MemberNotNullWhenAttribute` ([§23.5.7.9](attributes.md#23579-the-membernotnullwhen-attribute)) | The listed member will not be null when the method returns the specified `bool` value. -`DoesNotReturnAttribute` ([§23.5.7.4](attributes.md#23574-the-doesnotreturn-attribute)) | This method never returns. -`DoesNotReturnIfAttribute` ([§23.5.7.5](attributes.md#23575-the-doesnotreturnif-attribute)) | This method never returns if the associated `bool` parameter has the specified value. +| **Attribute** | **Meaning** | +| --- | --- | +| `AllowNullAttribute` ([§23.5.7.2](attributes.md#23572-the-allownull-attribute)) | A non-nullable argument may be null. | +| `DisallowNullAttribute` ([§23.5.7.3](attributes.md#23573-the-disallownull-attribute)) | A nullable argument should never be null. | +| `MaybeNullAttribute` ([§23.5.7.6](attributes.md#23576-the-maybenull-attribute)) | A non-nullable return value may be null. | +| `NotNullAttribute` ([§23.5.7.10](attributes.md#235710-the-notnull-attribute)) | A nullable return value will never be null. | +| `MaybeNullWhenAttribute` ([§23.5.7.7](attributes.md#23577-the-maybenullwhen-attribute)) | A non-nullable argument may be null when the method returns the specified `bool` value. | +| `NotNullWhenAttribute` ([§23.5.7.12](attributes.md#235712-the-notnullwhen-attribute)) | A nullable argument will not be null when the method returns the specified `bool` value. | +| `NotNullIfNotNullAttribute` ([§23.5.7.11](attributes.md#235711-the-notnullifnotnull-attribute)) | A return value is not null if the argument for the specified parameter is not null. | +| `MemberNotNullAttribute` ([§23.5.7.8](attributes.md#23578-the-membernotnull-attribute)) | The listed member will not be null when the method returns. | +| `MemberNotNullWhenAttribute` ([§23.5.7.9](attributes.md#23579-the-membernotnullwhen-attribute)) | The listed member will not be null when the method returns the specified `bool` value. | +| `DoesNotReturnAttribute` ([§23.5.7.4](attributes.md#23574-the-doesnotreturn-attribute)) | This method never returns. | +| `DoesNotReturnIfAttribute` ([§23.5.7.5](attributes.md#23575-the-doesnotreturnif-attribute)) | This method never returns if the associated `bool` parameter has the specified value. | The following subclauses in [§23.5.7](attributes.md#2357-code-analysis-attributes) are conditionally normative. @@ -1315,6 +1316,29 @@ Specifies that a nullable argument will not be `null` when the method returns th > > *end example* +### §UnscopedRefAttribute The UnscopedRef attribute + +`System.Diagnostics.CodeAnalysis.UnscopedRefAttribute` widens the ref-safe-context of a parameter, including the implicit `this` parameter, according to the following table: + +| UnscopedRef applied to | Original ref-safe-context | New ref-safe-context | +| --- | --- | --- | +| struct instance method or property (applies to `this`) | function-member | return-only | +| `in` / `ref` parameter | return-only | caller-context | +| `out` parameter | function-member | return-only | + +The permitted targets are: + +- A struct instance method or property, other than an `init` accessor or constructor, that does not implement an interface member. +- A `ref`, `in`, or `out` parameter that is not explicitly declared `scoped`, including an ordinary `ref` or `in` parameter. + +An application to any other target is a compile-time error. + +See §scoped-modifier for more information. + +### §ScopedRefAttribute The ScopedRef attribute + +The name `System.Runtime.CompilerServices.ScopedRefAttribute` is reserved for compiler use. The compiler emits this attribute on a parameter when the parameter's `scoped` annotation differs from its default state, in order to encode the `scoped` modifier (§scoped-modifier) in metadata. This attribute is not permitted in source. + ### 23.5.8 The EnumeratorCancellation attribute Specifies the parameter representing the `CancellationToken` for an asynchronous iterator ([§15.15](classes.md#1515-synchronous-and-asynchronous-iterators)). The argument for this parameter shall be combined with the argument passed to `IAsyncEnumerable.GetAsyncEnumerator(CancellationToken)`. This combined token shall be polled by `IAsyncEnumerator.MoveNextAsync()` ([§15.15.5.2](classes.md#151552-advance-the-enumerator)). The tokens shall be combined into a single token as if by `CancellationToken.CreateLinkedTokenSource` and its `Token` property. The combined token will be canceled if either of the two source tokens are canceled. The combined token is seen as the argument to the asynchronous iterator method ([§15.15](classes.md#1515-synchronous-and-asynchronous-iterators)) in the body of that method. diff --git a/standard/basic-concepts.md b/standard/basic-concepts.md index 845a86529..b9d1fe0ba 100644 --- a/standard/basic-concepts.md +++ b/standard/basic-concepts.md @@ -625,11 +625,11 @@ The following accessibility constraints exist: Methods, instance constructors, indexers, and operators are characterized by their ***signature***s: -- The signature of a method consists of the name of the method, the number of type parameters, and the type and parameter-passing mode of each of its parameters, considered in the order left to right. For these purposes, any type parameter of the method that occurs in the type of a parameter is identified not by its name, but by its ordinal position in the type parameter list of the method. The signature of a method specifically does not include the return type, parameter names, type parameter names, type parameter constraints, the `params` or `this` parameter modifiers, nor whether parameters are required or optional. +- The signature of a method consists of the name of the method, the number of type parameters, and the type and parameter-passing mode of each of its parameters, considered in the order left to right. For these purposes, any type parameter of the method that occurs in the type of a parameter is identified not by its name, but by its ordinal position in the type parameter list of the method. The signature of a method specifically does not include the return type, parameter names, type parameter names, type parameter constraints, the `params`, `scoped`, or `this` parameter modifiers, nor whether parameters are required or optional. - The signature of an instance constructor consists of the type and parameter-passing mode of each of its parameters, considered in the order left to right. The signature of an instance constructor specifically does not include the `params` modifier that may be specified for the right-most parameter, nor whether parameters are required or optional. -- The signature of an indexer consists of the type of each of its parameters, considered in the order left to right. The signature of an indexer specifically does not include the element type, nor does it include the `params` modifier that may be specified for the right-most parameter, nor whether parameters are required or optional. -- The signature of an operator consists of the name of the operator and the type of each of its parameters, considered in the order left to right. The signature of an operator specifically does not include the result type. -- The signature of a conversion operator consists of the source type and the target type. The implicit or explicit classification of a conversion operator is not part of the signature. +- The signature of an indexer consists of the type of each of its parameters, considered in the order left to right. The signature of an indexer specifically does not include the element type, or the `scoped` modifier, nor does it include the `params` modifier that may be specified for the right-most parameter, or the `scoped` modifier, nor whether parameters are required or optional. +- The signature of an operator consists of the name of the operator and the type of each of its parameters, considered in the order left to right. The signature of an operator specifically does not include the result type or the `scoped` modifier. +- The signature of a conversion operator consists of the source type and the target type. The implicit or explicit classification of a conversion operator is not part of the signature nor is the `scoped` modifier. - Two signatures of the same member kind (method, instance constructor, indexer or operator) are considered to be the *same signatures* if they have the same name, number of type parameters, number of parameters, and parameter-passing modes, and an identity conversion exists between the types of their corresponding parameters ([§10.2.2](conversions.md#1022-identity-conversion)). Signatures are the enabling mechanism for ***overloading*** of members in classes, structs, and interfaces: diff --git a/standard/classes.md b/standard/classes.md index 7f702e22f..8afceb468 100644 --- a/standard/classes.md +++ b/standard/classes.md @@ -1700,6 +1700,10 @@ The value of a field is obtained in an expression using a *simple_name* ([§12.8 A field declaration that declares multiple fields is equivalent to multiple declarations of single fields with the same attributes, modifiers, and type. +> *Note*: Inside a `ref struct`, a field may also be declared as a reference variable; see §Ref-Fields. *end note* + + + > *Example*: > > @@ -2255,8 +2259,9 @@ default_argument parameter_modifier : parameter_mode_modifier - | 'this' parameter_mode_modifier? - | parameter_mode_modifier? 'this' + | 'this' 'scoped'? parameter_mode_modifier? + | 'scoped'? parameter_mode_modifier? 'this' + | 'scoped' parameter_mode_modifier? ; parameter_mode_modifier @@ -2272,7 +2277,11 @@ parameter_array The parameter list consists of one or more comma-separated parameters of which only the last may be a *parameter_array*. -A *fixed_parameter* consists of an optional set of *attributes* ([§23](attributes.md#23-attributes)); an optional `in`, `out`, `ref`, or `this` modifier; a *type*; an *identifier*; and an optional *default_argument*. Each *fixed_parameter* declares a parameter of the given type with the given name. The `this` modifier designates the method as an extension method and is only allowed on the first parameter of a static method in a non-generic, non-nested static class. If the parameter is a `struct` type or a type parameter constrained to a `struct`, the `this` modifier may be combined with either the `ref` or `in` modifier, but not the `out` modifier. Extension methods are further described in [§15.6.10](classes.md#15610-extension-methods). A *fixed_parameter* with a *default_argument* is known as an ***optional parameter***, whereas a *fixed_parameter* without a *default_argument* is a ***required parameter***. A required parameter shall not appear after an optional parameter in a *parameter_list*. +A *fixed_parameter* consists of an optional set of *attributes* ([§23](attributes.md#23-attributes)); an optional `this` modifier; an optional `scoped` modifier; an optional `in`, `out`, `ref` modifier; a *type*; an *identifier*; and an optional *default_argument*. Each *fixed_parameter* declares a parameter of the given type with the given name. The `this` modifier designates the method as an extension method and is only allowed on the first parameter of a static method in a non-generic, non-nested static class. If the parameter is a `struct` type or a type parameter constrained to a `struct`, the `this` modifier may be combined with either the `ref` or `in` modifier, but not the `out` modifier. Extension methods are further described in [§15.6.10](classes.md#15610-extension-methods). A *fixed_parameter* with a *default_argument* is known as an ***optional parameter***, whereas a *fixed_parameter* without a *default_argument* is a ***required parameter***. A required parameter shall not appear after an optional parameter in a *parameter_list*. + +An output parameter implicitly has the `scoped` modifier. + +For a discussion of `scoped`, see §scoped-modifier. A parameter with a `ref`, `out` or `this` modifier cannot have a *default_argument*. An input parameter may have a *default_argument*. The *expression* in a *default_argument* shall be one of the following: @@ -2344,7 +2353,7 @@ The following kinds of parameters exist: - Reference parameters ([§15.6.2.3.3](classes.md#156233-reference-parameters)). - Parameter arrays ([§15.6.2.4](classes.md#15624-parameter-arrays)). -> *Note*: As described in [§7.5](basic-concepts.md#75-signatures-and-overloading), the `in`, `out`, and `ref` modifiers are part of a method’s signature, but the `params` modifier is not. *end note* +> *Note*: As described in [§7.5](basic-concepts.md#75-signatures-and-overloading), the `in`, `out`, and `ref` modifiers are part of a method’s signature, but the `params` and `scoped` modifiers are not. *end note* #### 15.6.2.2 Value parameters @@ -2378,6 +2387,8 @@ It is a compile-time error to modify the value of an input parameter. > *Note*: The primary purpose of input parameters is for efficiency. When the type of a method parameter is a large struct (in terms of memory requirements), it is useful to be able to avoid copying the whole value of the argument when calling the method. Input parameters allow methods to refer to existing values in memory, while providing protection against unwanted changes to those values. *end note* +An input parameter may carry the `scoped` modifier (§scoped-modifier) or the `[UnscopedRef]` attribute (§UnscopedRefAttribute). + ##### 15.6.2.3.3 Reference parameters A parameter declared with a `ref` modifier is a ***reference parameter***. For definite-assignment rules, see [§9.2.6](variables.md#926-reference-parameters). @@ -2441,7 +2452,9 @@ A parameter declared with a `ref` modifier is a ***reference parameter***. For d > > *end example* -For a `struct` type, within an instance method, instance accessor ([§12.2.1](expressions.md#1221-general)), or instance constructor with a constructor initializer, the `this` keyword behaves exactly as a reference parameter of the struct type ([§12.8.14](expressions.md#12814-this-access)). +For a `struct` type, within an instance method, instance accessor ([§12.2.1](expressions.md#1221-general)), or instance constructor with a constructor initializer, the `this` keyword behaves exactly as a reference parameter of the struct type ([§12.8.14](expressions.md#12814-this-access)). The `this` parameter of a struct instance method is implicitly `scoped ref` (§scoped-modifier). + +A reference parameter may carry the `scoped` modifier (§scoped-modifier) or the `[UnscopedRef]` attribute (§UnscopedRefAttribute). ##### 15.6.2.3.4 Output parameters @@ -2449,6 +2462,8 @@ A parameter declared with an `out` modifier is an ***output parameter***. For de A method declared as an optional partial method ([§15.6.9.2](classes.md#15692-optional-partial-methods)) shall not have output parameters. +An output parameter is implicitly `scoped` (§scoped-modifier); the `[UnscopedRef]` attribute (§UnscopedRefAttribute) may be applied to widen its ref-safe-context. + > *Note*: Output parameters are typically used in methods that produce multiple return values. *end note* diff --git a/standard/expressions.md b/standard/expressions.md index 142e87ff6..92d6278dd 100644 --- a/standard/expressions.md +++ b/standard/expressions.md @@ -567,8 +567,8 @@ argument_value : expression | 'in' variable_reference | 'ref' variable_reference - | 'out' declaration_expression | 'out' variable_reference + | 'out' declaration_expression ; ``` @@ -577,10 +577,10 @@ An *argument_list* consists of one or more *argument*s, separated by commas. Eac The *argument_value* can take one of the following forms: - An *expression*, indicating that the argument is passed as a value parameter or is transformed into an input parameter and then passed as that, as determined by [§12.6.4.2](expressions.md#12642-applicable-function-member) and described in [§12.6.2.3](expressions.md#12623-run-time-evaluation-of-argument-lists). An *interpolated_string_handler_expression* converted to a struct handler can also be passed to a reference parameter through a temporary, as specified in those clauses. -- The keyword `in` followed by a *variable_reference* ([§9.5](variables.md#95-variable-references)), indicating that the argument is passed as an input parameter ([§15.6.2.3.2](classes.md#156232-input-parameters)). A variable shall be definitely assigned ([§9.4](variables.md#94-definite-assignment)) before it can be passed as an input parameter. -- The keyword `ref` followed by a *variable_reference* ([§9.5](variables.md#95-variable-references)), indicating that the argument is passed as a reference parameter ([§15.6.2.3.3](classes.md#156233-reference-parameters)). A variable shall be definitely assigned ([§9.4](variables.md#94-definite-assignment)) before it can be passed as a reference parameter. -- The keyword `out` followed by a *variable_reference* ([§9.5](variables.md#95-variable-references)), indicating that the argument is passed as an output parameter ([§15.6.2.3.4](classes.md#156234-output-parameters)). A variable is considered definitely assigned ([§9.4](variables.md#94-definite-assignment)) following a function member invocation in which the variable is passed as an output parameter. -- The keyword `out` followed by a *declaration_expression* ([§12.20](expressions.md#1220-declaration-expressions)), indicating that a new local variable is declared, and then passed as an output parameter ([§15.6.2.3.4](classes.md#156234-output-parameters)). The newly-declared variable is considered definitely assigned ([§9.4](variables.md#94-definite-assignment)) following the function member invocation. +- The keyword `in`, followed by a *variable_reference* ([§9.5](variables.md#95-variable-references)), indicating that the argument is passed as an input parameter ([§15.6.2.3.2](classes.md#156232-input-parameters)). A variable shall be definitely assigned ([§9.4](variables.md#94-definite-assignment)) before it can be passed as an input parameter. +- The keyword `ref`, followed by a *variable_reference* ([§9.5](variables.md#95-variable-references)), indicating that the argument is passed as a reference parameter ([§15.6.2.3.3](classes.md#156233-reference-parameters)). A variable shall be definitely assigned ([§9.4](variables.md#94-definite-assignment)) before it can be passed as a reference parameter. +- The keyword `out`, followed by a *variable_reference* ([§9.5](variables.md#95-variable-references)), indicating that the argument is passed as an output parameter ([§15.6.2.3.4](classes.md#156234-output-parameters)). A variable is considered definitely assigned ([§9.4](variables.md#94-definite-assignment)) following a function member invocation in which the variable is passed as an output parameter. +- The keyword `out`, followed by a *declaration_expression* ([§12.20](expressions.md#1220-declaration-expressions)), indicating that a new local variable is declared, and then passed as an output parameter ([§15.6.2.3.4](classes.md#156234-output-parameters)). The newly-declared variable is considered definitely assigned ([§9.4](variables.md#94-definite-assignment)) following the function member invocation. A `scoped` modifier, if present, is part of the declaration expression (§scoped-modifier). The form determines the ***parameter-passing mode*** of the argument: *value*, *input*, *reference*, or *output*, respectively (where both forms using the `out` keyword use the output passing mode). However, an argument with value passing mode might be passed to an input parameter or, for an interpolated string handler conversion, to a reference parameter as described above. @@ -2788,6 +2788,7 @@ initializer_target initializer_value : expression + | 'ref' variable_reference | object_or_collection_initializer ; ``` @@ -2796,12 +2797,14 @@ An object initializer consists of a sequence of member initializers, enclosed by > *Note*: While an object initializer is not permitted to set the same field or property more than once, there are no such restrictions for indexers. An object initializer may contain multiple initializer targets referring to indexers, and may even use the same indexer arguments multiple times. *end note* -Each *initializer_target* is followed by an equals sign and either an expression, an object initializer or a collection initializer. It is not possible for expressions within the object initializer to refer to the newly created object it is initializing. +Each *initializer_target* is followed by an equals sign and either an expression, `ref` followed by a *variable_reference*, an object initializer or a collection initializer. It is not possible for expressions within the object initializer to refer to the newly created object it is initializing. In the *argument_list* of an *initializer_target* there is no implicit support for arguments of type `Index` ([§18.4.2](ranges.md#1842-implicit-index-support)) or `Range` ([§18.4.3](ranges.md#1843-implicit-range-support)). A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment ([§12.24.2](expressions.md#12242-simple-assignment)) to the target. +A member initializer that specifies `ref` followed by a *variable_reference* retargets a ref field of the object being initialized. It is processed as a ref assignment ([§12.24.4](expressions.md#12244-ref-assignment)) to that field, including the requirements on the target, identity conversion, writability, and safe-contexts. + A member initializer that specifies an object initializer after the equals sign is a ***nested object initializer***, i.e., an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property. Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type. A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the target field, property, or indexer, the elements given in the initializer are added to the collection referenced by the target. The target shall be of a collection type that satisfies the requirements specified in [§12.8.17.2.3](expressions.md#1281723-collection-initializers). @@ -3570,6 +3573,10 @@ A *default_value_expression* is a constant expression ([§12.26](expressions.md# - one of the following value types: `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `nint`, `nuint`, `long`, `ulong`, `char`, `float`, `double`, `decimal`, `bool`; or - any enumeration type. +A reference variable field `rv` of type `T` shall not have an explicit initializer of `default`. + +> *Note*: If one tries to initialize `rv` using `rv = default`, this does not set the reference variable to `null`. Instead, it attempts to set the value of the (possibly non-existent) referent to the default value for type `T`. *end note* + ### 12.8.22 Stack allocation A stack allocation expression allocates a block of memory from the execution stack. The ***execution stack*** is an area of memory where local variables are stored. The execution stack is not part of the managed heap. The memory used for local variable storage is automatically recovered when the current function returns. @@ -4046,6 +4053,10 @@ Each *identifier* in the *member_initializer_list* shall name an accessible inst For a receiver other than an anonymous type, each member initializer is subject to the same rules as an assignment to the corresponding member of a variable of the receiver's type. A property assignment requires an accessible `set` or `init` accessor, but does not require a `get` accessor. An `init` accessor is permitted in this context ([§15.7.3](classes.md#1573-accessors)); the usual accessibility and readonly-field restrictions apply. +A member initializer specifying `ref` followed by a *variable_reference* is processed as a ref assignment to a ref field of the copy, as specified for object initializers ([§12.8.17.2.2](expressions.md#1281722-object-initializers)). + +For a ref struct receiver, the safe-context of the result is determined by §object-initializer-safe-context, using the safe-context of the receiver in place of that of a constructor invocation. + For an anonymous-type receiver, each initializer shall specify an expression implicitly convertible to the type of the named property. The absence of a setter on that property does not prevent its initialization by a *with_expression*. The type of the result is the compile-time type of the receiver. At run time, the receiver is evaluated once, before any member initializer expressions. Subsequent evaluation depends on its compile-time type: @@ -5419,7 +5430,7 @@ A declaration expression declares a local variable. ```ANTLR declaration_expression - : local_variable_type identifier + : 'scoped'? local_variable_type identifier ; local_variable_type @@ -5428,6 +5439,8 @@ local_variable_type ; ``` +'scoped' shall only be permitted with *local_variable_type* if *local_variable_type* is 'var' or a ref struct type, and *identifer* is not a discard. + The *simple_name* `_` is also considered a declaration expression if simple name lookup did not find an associated declaration ([§12.8.4](expressions.md#1284-simple-names)). When used as a declaration expression, `_` is called a *simple discard*. It is semantically equivalent to `var _`, but is permitted in more places. A declaration expression only occurs in the following syntactic contexts: @@ -5590,7 +5603,7 @@ explicit_anonymous_function_parameter_list ; explicit_anonymous_function_parameter - : attributes? anonymous_function_parameter_modifier? type identifier + : attributes? 'scoped'? anonymous_function_parameter_modifier? type identifier ; anonymous_function_parameter_modifier @@ -5623,6 +5636,8 @@ anonymous_function_body If the modifier `static` is present, the anonymous function cannot capture state from the enclosing scope. A `static` anonymous function may reference `static` members, type parameters, and constant definitions from the enclosing scope. +For a discussion of `scoped`, see §scoped-modifier. + 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. @@ -5695,6 +5710,8 @@ A *block* body of an anonymous function is always reachable ([§13.2](statements > var concat = string ([DisallowNull] string a, [DisallowNull] string b) => a + b; > Func parse = [X][return: Y] ([Z] s) > => (s is not null) ? int.Parse(s) : null; +> var lambda = (in int p1, out bool p2, scoped ref float p3, +> scoped Span p4) => Mlam(in p1, out p2, ref p3, p4); > ``` > > *end example* @@ -7513,13 +7530,17 @@ The operator `= ref` is called the ***ref assignment operator***. The expressio The left operand shall be an expression that binds to a reference variable ([§9.7](variables.md#97-reference-variables-and-returns)), a reference parameter (other than `this`), an output parameter, an input parameter, or a discard. When the left operand is a discard, the right operand is evaluated but no variable reference is stored. Otherwise, the right operand shall be an expression that yields a *variable_reference* ([§9.5](variables.md#95-variable-references)) designating a value of the same type as the left operand. -It is a compile time error if the ref-safe-context ([§9.7.2](variables.md#972-ref-safe-contexts)) of the left operand is wider than the ref-safe-context of the right operand. +When the left operand designates a ref field, ref assignment is subject to the readonly-field restrictions in §Ref-Fields. An identity conversion ([§10.2.2](conversions.md#1022-identity-conversion)) shall exist from the type of the right operand to the field type. + +The ref-safe-context of the right operand shall be at least as wide as the ref-safe-context of the left operand, and the left operand shall have the same safe-context as the right operand (§9.7.2). + +> *Note*: This requirement exists because the lifetime of the value pointed to by a ref location is invariant. The indirection prevents one from allowing any kind of variance here, even to narrower lifetimes. *end note* The right operand shall be definitely assigned at the point of the ref assignment. When the left operand binds to an output parameter, it is an error if that output parameter has not been definitely assigned at the beginning of the ref assignment operator. -If the left operand is a writeable ref (i.e., it designates anything other than a `ref readonly` local or input parameter), then the right operand shall be a writeable *variable_reference*. If the right operand variable is writeable, the left operand may be a writeable or read-only ref. +If the left operand designates a writable referent (rather than a `ref readonly` local, a `ref readonly` field, or an input parameter), then the right operand shall be a writeable *variable_reference*. If the right operand variable is writeable, the left operand may designate a writable or read-only referent. The operation makes the left operand an alias of the right operand variable. The alias may be made read-only even if the right operand variable is writeable. diff --git a/standard/lexical-structure.md b/standard/lexical-structure.md index 86a73301c..91b0ed238 100644 --- a/standard/lexical-structure.md +++ b/standard/lexical-structure.md @@ -629,9 +629,9 @@ contextual_keyword | 'group' | 'init' | 'into' | 'join' | 'let' | 'managed' | 'nameof' | 'nint' | 'not' | 'notnull' | 'nuint' | 'on' | 'or' | 'orderby' | 'partial' - | 'record' | 'remove' | 'select' | 'set' | 'Stdcall' - | 'Thiscall' | 'unmanaged' | 'value' | 'var' | 'when' - | 'where' | 'yield' + | 'record' | 'remove' | 'scoped' | 'select' | 'set' + | 'Stdcall' | 'Thiscall' | 'unmanaged' | 'value' | 'var' + | 'when' | 'where' | 'yield' ; ``` diff --git a/standard/standard-library.md b/standard/standard-library.md index 5e491c7a2..94b763da4 100644 --- a/standard/standard-library.md +++ b/standard/standard-library.md @@ -384,6 +384,7 @@ namespace System.Runtime.CompilerServices public static class Unsafe { public static ref T NullRef(); + public static bool IsNullRef(ref T source); } } @@ -777,6 +778,15 @@ namespace System.Diagnostics.CodeAnalysis { public NotNullWhenAttribute(bool returnValue); } + + [System.AttributeUsage(System.AttributeTargets.Method + | System.AttributeTargets.Parameter + | System.AttributeTargets.Property, + AllowMultiple=false, Inherited=false)] + public sealed class UnscopedRefAttribute : Attribute + { + public UnscopedRefAttribute(); + } } namespace System.Linq.Expressions @@ -798,11 +808,11 @@ namespace System.Runtime.CompilerServices int formattedCount, IFormatProvider? provider); public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span initialBuffer); - public void AppendFormatted(ReadOnlySpan value); + public void AppendFormatted(scoped ReadOnlySpan value); public void AppendFormatted(string? value); public void AppendFormatted(object? value, int alignment = 0, string? format = default); - public void AppendFormatted(ReadOnlySpan value, + public void AppendFormatted(scoped ReadOnlySpan value, int alignment = 0, string? format = default); public void AppendFormatted(string? value, int alignment = 0, string? format = default); @@ -1479,6 +1489,7 @@ The following library types are referenced in this specification. The full names - `global::System.Diagnostics.CodeAnalysis.NotNullAttribute` - `global::System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute` - `global::System.Diagnostics.CodeAnalysis.NotNullWhenAttribute` +- `global::System.Diagnostics.CodeAnalysis.UnscopedRefAttribute` - `global::System.Linq.Expressions.Expression` - `global::System.Reflection.MemberInfo` - `global::System.Runtime.CompilerServices.AsyncMethodBuilderAttribute` diff --git a/standard/statements.md b/standard/statements.md index 7eff86545..a6862ebe3 100644 --- a/standard/statements.md +++ b/standard/statements.md @@ -354,8 +354,8 @@ The ref-safe-context ([§9.7.2](variables.md#972-ref-safe-contexts)) of a ref lo ```ANTLR implicitly_typed_local_variable_declaration - : 'var' implicitly_typed_local_variable_declarator - | ref_kind 'var' ref_local_variable_declarator + : 'scoped'? 'var' implicitly_typed_local_variable_declarator + | 'scoped'? ref_kind 'var' ref_local_variable_declarator ; implicitly_typed_local_variable_declarator @@ -365,9 +365,11 @@ implicitly_typed_local_variable_declarator An *implicitly_typed_local_variable_declaration* introduces a single local variable, *identifier*. The *expression* or *variable_reference* shall have a compile-time type, `T`, except that for an *expression* that is an anonymous function or method group with an anonymous function type ([§12.22.8](expressions.md#12228-anonymous-function-type)), `T` is its corresponding delegate type. The first alternative declares a variable with an initial value of *expression* converted to `T`; its type is `T?` when `T` is a non-nullable reference type, otherwise its type is `T`. The second alternative declares a ref variable with an initial value of `ref` *variable_reference*; its type is `ref T?` when `T` is a non-nullable reference type, otherwise its type is `ref T`. (*ref_kind* is described in [§15.6.1](classes.md#1561-general).) +For a discussion of `scoped`, see §scoped-modifier. + > *Example*: > -> +> > ```csharp > var i = 5; > var s = "Hello"; @@ -376,11 +378,12 @@ An *implicitly_typed_local_variable_declaration* introduces a single local varia > var orders = new Dictionary(); > ref var j = ref i; > ref readonly var k = ref i; +> scoped var r = new RS(ref i); // ref struct RS { ref int Field; ... } > ``` > > The implicitly typed local variable declarations above are precisely equivalent to the following explicitly typed declarations: > -> +> > ```csharp > int i = 5; > string s = "Hello"; @@ -389,17 +392,19 @@ An *implicitly_typed_local_variable_declaration* introduces a single local varia > Dictionary orders = new Dictionary(); > ref int j = ref i; > ref readonly int k = ref i; +> scoped RS r = new RS(ref i); // ref struct RS { ref int Field; ... } > ``` > > The following are incorrect implicitly typed local variable declarations: > -> +> > ```csharp > var x; // Error, no initializer to infer type from > var y = {1, 2, 3}; // Error, array initializer not permitted > var z = null; // Error, null does not have a type > var u = x => x + 1; // Error, no natural type > var v = v++; // Error, initializer cannot refer to v itself +> scoped var i = 10; // Error, i must be a ref or ref struct > ``` > > *end example* @@ -424,7 +429,7 @@ Anonymous functions and method groups with anonymous function types may not be u ```ANTLR explicitly_typed_local_variable_declaration - : type explicitly_typed_local_variable_declarators + : 'scoped'? type explicitly_typed_local_variable_declarators ; explicitly_typed_local_variable_declarators @@ -446,11 +451,13 @@ An *explicitly_typed_local_variable_declaration* introduces one or more local va If a *local_variable_initializer* is present then its type shall be appropriate according to the rules of simple assignment ([§12.24.2](expressions.md#12242-simple-assignment)) or array initialization ([§17.7](arrays.md#177-array-initializers)) and its value is assigned as the initial value of the variable. +For a discussion of `scoped`, see §scoped-modifier. + #### 13.6.2.4 Explicitly typed ref local variable declarations ```ANTLR explicitly_typed_ref_local_variable_declaration - : ref_kind type ref_local_variable_declarators + : 'scoped'? ref_kind type ref_local_variable_declarators ; ref_local_variable_declarators @@ -462,12 +469,16 @@ ref_local_variable_declarator ; ``` +An *explicitly_typed_ref_local_variable_declaration* introduces one or more local ref variables with the specified `scoped` modifier and *type*. + The initializing *variable_reference* shall have type *type* and meet the same requirements as for a *ref assignment* ([§12.24.4](expressions.md#12244-ref-assignment)). If *ref_kind* is `ref readonly`, the *identifier*s being declared are references to variables that are treated as read-only. Otherwise, if *ref_kind* is `ref`, the *identifier*s being declared are references to variables that shall be writable. It is a compile-time error to declare a ref local variable, or a variable of a `ref struct` type, within a method declared with the *method_modifier* `async`, or within an iterator ([§15.15](classes.md#1515-synchronous-and-asynchronous-iterators)). +For a discussion of `scoped`, see §scoped-modifier. + ### 13.6.3 Local constant declarations A *local_constant_declaration* declares one or more local constants. @@ -1132,7 +1143,7 @@ The `foreach` statement enumerates the elements of a collection, executing an em ```ANTLR foreach_statement : // synchronous foreach - 'foreach' '(' ref_kind? local_variable_type identifier 'in' expression ')' + 'foreach' '(' 'scoped'? ref_kind? local_variable_type identifier 'in' expression ')' embedded_statement | // asynchronous foreach 'await' 'foreach' '(' local_variable_type identifier 'in' expression ')' @@ -1145,6 +1156,10 @@ foreach_statement There are three forms of the *foreach_statement*: *synchronous*, *asynchronous* and *deconstructing*; corresponding to the three alternatives of the above grammar. +It is a compile-time error for `scoped` to be present in a *foreach_statement* unless a *ref_kind* is also present or the *local_variable_type* denotes a ref struct type. + +The prohibition on ref locals and locals of ref struct type in an `async` method ([§13.6.2.4](statements.md#13624-explicitly-typed-ref-local-variable-declarations)) applies to iteration variables as well. + The deconstructing foreach supports both synchronous and asynchronous forms and is described in [§13.9.5.4](statements.md#13954-deconstructing-foreach). The *local_variable_type* and *identifier* of a foreach statement declare the ***iteration variable*** of the statement. If the `var` identifier is given as the *local_variable_type*, and no type named `var` is in scope, the iteration variable is said to be an ***implicitly typed iteration variable***, and its type is taken to be the element type of the `foreach` statement, as specified below. @@ -1153,6 +1168,8 @@ If the *foreach_statement* contains both or neither `ref` and `readonly`, the it The iteration variable corresponds to a local variable with a scope that extends over the embedded statement. During execution of a `foreach` statement, the iteration variable represents the collection element for which an iteration is currently being performed. If the iteration variable denotes a read-only variable, a compile-time error occurs if the embedded statement attempts to modify it (via assignment or the `++` and `--` operators) or pass it as a reference or output parameter. +For a discussion of `scoped`, see §scoped-modifier. + The compile-time processing of a `foreach` statement first determines the ***collection type*** (`C`), ***enumerator type*** (`E`) and ***iteration type*** (`T`, `ref T` or `ref readonly T`) of the expression. The determination is similar for the synchronous and asynchronous versions. Different interfaces with different methods and return types distinguish the synchronous and asynchronous versions. The general process proceeds as follows. Names within ‘«’ and ‘»’ are placeholders for the actual names for synchronous and asynchronous iterators. The types allowed for «GetEnumerator», «MoveNext», «IEnumerable»\, «IEnumerator»\, and any other distinctions are detailed in [§13.9.5.2](statements.md#13952-synchronous-foreach) for a synchronous `foreach` statement, and in [§13.9.5.3](statements.md#13953-asynchronous-foreach) for an asynchronous `foreach` statement. @@ -1477,7 +1494,7 @@ This follows the behavior of synchronous foreach ([§13.9.5.2](statements.md#139 - `C` and `E` are determined as for synchronous foreach - `e` is not visible or accessible anywhere in the program except as indicated in the above code -- the variables declared within the «deconstructor» are read-only to the «embedded_statement» +- the variables declared by the «deconstructor» are read-only to the «embedded_statement» - the code in the `finally` block is determined as for synchronous foreach An `await foreach` statement of the form: diff --git a/standard/structs.md b/standard/structs.md index 44c310734..12aba2a4f 100644 --- a/standard/structs.md +++ b/standard/structs.md @@ -141,7 +141,7 @@ The members of a struct consist of the members introduced by its *struct_member_ ```ANTLR struct_member_declaration : constant_declaration - | field_declaration + | struct_field_declaration | method_declaration | property_declaration | event_declaration @@ -156,7 +156,9 @@ struct_member_declaration *fixed_size_buffer_declaration* ([§24.8.2](unsafe-code.md#2482-fixed-size-buffer-declarations)) is only available in unsafe code ([§24](unsafe-code.md#24-unsafe-code)). -> *Note*: All kinds of *class_member_declaration*s except *finalizer_declaration* are also *struct_member_declaration*s. *end note* +> *Note*: A *struct_member_declaration* includes all *class_member_declaration* alternatives except *finalizer_declaration*, and adds *struct_field_declaration* which supports ref fields (§Ref-Fields). *end note* + +Fields in structs support capabilities not supported in classes. See §Ref-Fields for details. Except for the differences noted in [§16.6](structs.md#166-class-and-struct-differences), the descriptions of class members provided in [§15.3](classes.md#153-class-members) through [§15.12](classes.md#1512-static-constructors) apply to struct members as well. @@ -544,7 +546,7 @@ A variable of a struct type directly contains the data of the struct, whereas a With classes, it is possible for two variables to reference the same object, and thus possible for operations on one variable to affect the object referenced by the other variable. With structs, the variables each have their own copy of the data (except in the case of by-reference parameters), and it is not possible for operations on one to affect the other. Furthermore, except when explicitly nullable ([§8.3.12](types.md#8312-nullable-value-types)), it is not possible for values of a struct type to be `null`. -> *Note*: If a struct contains a field of reference type then the contents of the object referenced can be altered by other operations. However the value of the field itself, i.e., which object it references, cannot be changed through a mutation of a different struct value. *end note* +> *Note*: If a struct contains a field of reference type or that is a reference variable then the contents of the object referenced can be altered by other operations. However the value of the field itself, i.e., which object it references, cannot be changed through a mutation of a different struct value. *end note* @@ -599,7 +601,7 @@ When a property or indexer of a struct is the target of an assignment, the insta ### 16.6.5 Default values -As described in [§9.3](variables.md#93-default-values), several kinds of variables are automatically initialized to their default value when they are created. For variables of class types and other reference types, this default value is `null`. However, since structs are value types that cannot be `null`, the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to `null`. +As described in [§9.3](variables.md#93-default-values), several kinds of variables are automatically initialized to their default value when they are created. For variables of class types and other reference types, as well as reference variable fields, this default value is `null`. However, since structs are value types that cannot be `null`, the default value of a struct is the value produced by setting all instance fields to their default values as specified in that subclause. > *Example*: Referring to the `Point` struct declared above, the example > @@ -740,9 +742,11 @@ Similarly, boxing never implicitly occurs when accessing a member on a constrain > > *end example* -### 16.6.8 Field initializers +### §fields Fields + +#### §field-initializers Field initializers -As described in [§16.6.5](structs.md#1665-default-values), the default value of a struct consists of the value that results from setting all value type fields to their default value and all reference type fields to `null`. Static and instance fields of a struct are permitted to include variable initializers; however, in the case of an instance field initializer, at least one instance constructor shall also be declared, or for a record struct, a *delimited_parameter_list* shall be present. +The default value of a struct is described in [§16.6.5](structs.md#1665-default-values). Static and instance fields of a struct are permitted to include variable initializers; however, in the case of an instance field initializer, at least one instance constructor shall also be declared, or for a record struct, a *delimited_parameter_list* shall be present. > *Example*: > @@ -770,15 +774,90 @@ As described in [§16.6.5](structs.md#1665-default-values), the default value of > > *end example* -When a struct instance constructor has no constructor initializer, that constructor implicitly performs the initializations specified by the *variable_initializer*s of the instance fields declared in its struct. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor. +When a struct instance constructor has no constructor initializer, that constructor implicitly performs the initializations specified by the *variable_initializer*s and *ref_field_initializer*s of the instance fields declared in its struct. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor. -When a struct instance constructor has a `this()` constructor initializer that represents the default parameterless constructor, the declared constructor implicitly clears all instance fields and performs the initializations specified by the *variable_initializer*s of the instance fields declared in its struct. Immediately upon entry to the constructor, all value type fields are set to their default value and all reference type fields are set to `null`. Immediately after that, a sequence of assignments corresponding to the *variable_initializer*s are executed. +When a struct instance constructor has a `this()` constructor initializer that represents the default parameterless constructor, the declared constructor implicitly clears all instance fields and performs the initializations specified by the *variable_initializer*s and *ref_field_initializer*s of the instance fields declared in its struct. Immediately upon entry to the constructor, all instance fields are set to their default values ([§9.3](variables.md#93-default-values)). Immediately after that, a sequence of assignments corresponding to the field initializers are executed. A *field_declaration* declared directly inside a *struct_declaration* having the *struct_modifier* `readonly` shall have the *field_modifier* `readonly`. +#### §Ref-Fields Ref fields + +```ANTLR +struct_field_declaration + : field_declaration + | attributes? field_modifier* 'ref' 'readonly'? type + ref_field_declarators ';' + ; + +ref_field_declarators + : ref_field_declarator (',' ref_field_declarator)* + ; + +ref_field_declarator + : identifier ('=' ref_field_initializer)? + ; + +ref_field_initializer + : 'ref' variable_reference + ; +``` + +*field_modifier* is described in [§15.5.1](classes.md#1551-general). + +A *struct_field_declaration* that is a *field_declaration* is as described in [§15.5](classes.md#155-fields). + +A field declared with `ref`, optionally preceded or followed by `readonly`, is a reference variable and is subject to the following constraints: + +- It shall only be declared in a `ref struct`. +- It shall not be declared `static`, `volatile`, or `const`. +- Its type shall not itself be a `ref struct` type. +- In a `readonly ref struct`, every `ref` field shall be declared `readonly ref` (it may additionally be declared `readonly ref readonly`). + +A *ref_field_initializer* establishes the initial referent of a ref field. Its *variable_reference* shall be definitely assigned, and its ref-safe-context shall permit assignment to the field. An identity conversion ([§10.2.2](conversions.md#1022-identity-conversion)) shall exist from the type of the *variable_reference* to the field type without applying, directly or recursively, the rule for identity conversions between `object` and `dynamic`. For a field declared without `readonly` after `ref`, the *variable_reference* shall be writable. Subsequent assignments of a value through the field modify its referent; ref assignments ([§12.24.4](expressions.md#12244-ref-assignment)) change its referent. + +> *Note*: The restriction on identity conversions between `object` and `dynamic` is applied recursively to prohibit identity conversions between tuple element types, array element types, or corresponding generic type arguments with identity conversions between `object` and `dynamic`. *end note* + +Consider the following ref struct declaration: + + + +```csharp +ref struct RwS +{ + public static int rwField = 100; + + public ref int rwRefToRwData = ref rwField; + public ref readonly int rwRefToRoData = ref rwField; + public readonly ref int roRefToRwData = ref rwField; + public readonly ref readonly int roRefToRoData = ref rwField; + public RwS() { /*…*/ } +} +``` + +`rwRefToRwData` is a writable reference variable, whose referent is seen as a writable `int`. `rwRefToRoData` is a writable reference variable, whose referent is seen as a read-only `int`. `roRefToRwData` is a read-only reference variable, whose referent is seen as a writable `int`. `roRefToRoData` is a read-only reference variable, whose referent is seen as a read-only `int`. The read/write field `rwField` can be written directly, and via the reference variables `rwRefToRwData` and `roRefToRwData`. + +For a ref field, `readonly` before `ref` restricts changing its referent to its initializer or a ref assignment to the field on `this` within an instance constructor or `init` accessor of the declaring type. `readonly` after `ref` makes access to its referent read-only. + +Consider the following readonly ref struct declaration: + + + +```csharp +readonly ref struct RoS +{ + public static int rwField = 200; + + public readonly ref int roRefToRwData = ref rwField; + public readonly ref readonly int roRefToRoData = ref rwField; + public RoS() { /*...*/ } +} +``` + +`roRefToRwData` is a read-only reference variable, whose referent is seen as a writable `int`. `roRefToRoData` is a read-only reference variable, whose referent is seen as a read-only `int`. The read/write field `rwField` can be written directly, and via the reference variable `roRefToRwData`. + ### 16.6.9 Constructors -A struct can declare instance constructors, with zero or more parameters. If a struct has no explicitly declared parameterless instance constructor, one is synthesized, with public accessibility, which always returns the value that results from setting all value type fields to their default value and all reference type fields to `null` ([§8.3.3](types.md#833-default-constructors)). In such a case, any instance field initializers are ignored when that constructor executes. +A struct can declare instance constructors, with zero or more parameters. If a struct has no explicitly declared parameterless instance constructor, one is synthesized, with public accessibility, which always returns the default value of the struct ([§16.6.5](structs.md#1665-default-values)). In such a case, any instance field initializers are ignored when that constructor executes. An explicitly declared parameterless instance constructor shall have public accessibility. @@ -954,25 +1033,31 @@ For any non-default expression whose compile-time type is a ref struct has a saf The safe-context records which context a value may be copied into. Given an assignment from an expression `E1` with a safe-context `S1`, to an expression `E2` with safe-context `S2`, it is an error if `S2` is a wider context than `S1`. -There are three different safe-context values, the same as the ref-safe-context values defined for reference variables ([§9.7.2](variables.md#972-ref-safe-contexts)): **declaration-block**, **function-member**, and **caller-context**. The safe-context of an expression constrains its use as follows: +There are four different safe-context values, the same as the ref-safe-context values defined for reference variables ([§9.7.2](variables.md#972-ref-safe-contexts)): **declaration-block**, **function-member**, **return-only**, and **caller-context**. The safe-context of an expression constrains its use as follows: -- For a return statement `return e1`, the safe-context of `e1` shall be caller-context. +- For a return statement `return e1`, the safe-context of `e1` shall be at least return-only. - For an assignment `e1 = e2` the safe-context of `e2` shall be at least as wide a context as the safe-context of `e1`. - -For a method invocation if there is a `ref` or `out` argument of a `ref struct` type (including the receiver unless the type is `readonly`), with safe-context `S1`, then no argument (including the receiver) may have a narrower safe-context than `S1`. +- For an assignment to an `out` parameter, the safe-context of the right-hand side shall be at least return-only. #### 16.6.15.2 Parameter safe context -A parameter of a ref struct type, including the `this` parameter of an instance method, has a safe-context of caller-context. +A value parameter of ref struct type declared `scoped` has a safe-context of function-member. Otherwise, a parameter of a ref struct type, including the `this` parameter of an instance method, has a safe-context of caller-context, subject to the following exceptions. + +An `out` parameter of a ref struct type has a safe-context of return-only. + +A `this` parameter in a struct constructor has a safe-context of return-only. #### 16.6.15.3 Local variable safe context A local variable of a ref struct type has a safe-context as follows: -- If the variable is an iteration variable of a `foreach` loop, then the variable’s safe-context is the same as the safe-context of the `foreach` loop’s expression. +- If the variable is declared `scoped` without `ref`, its safe-context is declaration-block. +- Otherwise if the variable is an iteration variable of a `foreach` loop, then the variable’s safe-context is the same as the safe-context of the `foreach` loop’s expression. - Otherwise if the variable’s declaration has an initializer then the variable’s safe-context is the same as the safe-context of that initializer. - Otherwise the variable is uninitialized at the point of declaration and has a safe-context of caller-context. +See [§9.7.2.1](variables.md#9721-general) and [§9.7.2.2](variables.md#9722-local-variable-ref-safe-context). + #### 16.6.15.4 Field safe context A reference to a field `e.F`, where the type of `F` is a ref struct type, has a safe-context that is the same as the safe-context of `e`. @@ -987,27 +1072,182 @@ For an operator that yields a value, such as `e1 + e2` or `c ? e1 : e2`, the saf #### 16.6.15.6 Method and property invocation -A value resulting from a method invocation `e1.M(e2, ...)` or property invocation `e.P` has safe-context of the smallest of the following contexts: +A value resulting from a method invocation `e1.M(e2, ...)` or property invocation `e.P`, where `M()` does not return ref-to-ref-struct, has safe-context of the smallest of the following contexts: -- caller-context. -- The safe-context of all argument expressions (including the receiver). +- The caller-context. +- When the return is a `ref struct`, the safe-context contributed by all argument expressions (including the receiver). +- When the return is a `ref struct`, the ref-safe-context contributed by all reference arguments. + +If `M()` does return ref-to-ref-struct, the safe-context is the same as the safe-context of all arguments which are ref-to-ref-struct. It is an error if there are multiple such arguments with different safe-contexts. + +Argument contributions and the generalization of reference arguments to input and annotated output parameters are specified in [§9.7.2.6](variables.md#9726-function-invocation). They also apply to §method-arguments-must-match and §declaration-expression-safe-context. A property invocation (either `get` or `set`) is treated as a method invocation of the underlying method by the above rules. -#### 16.6.15.7 stackalloc +> *Example*: The following illustrates how `scoped` affects the safe-context of a method's return value: +> +> +> ```csharp +> ref struct RS +> { +> public ref int RefField; +> public RS(ref int i) { RefField = ref i; } +> } +> +> class C +> { +> static RS CreateAndCapture(ref int value) +> { +> // OK: ref-safe-context of `ref value` is caller-context, +> // safe-context contributed is caller-context. +> return new RS(ref value); +> } +> +> static RS CreateWithoutCapture(scoped ref int value) +> { +> // Error: `value` is scoped ref so it does not contribute +> // ref-safe-context. The constructor needs ref-safe-context +> // of caller-context but `value` only has function-member. +> return new RS(ref value); +> } +> } +> ``` +> +> *end example* -The result of a stackalloc expression has safe-context of function-member. +#### §method-arguments-must-match Method arguments must match -#### 16.6.15.8 Constructor invocations +For any method invocation `e.M(a1, a2, ... aN)`: -A `new` expression that invokes a constructor obeys the same rules as a method invocation that is considered to return the type being constructed. +1. Calculate the narrowest safe-context from: + - caller-context. + - The safe-context contributed by all arguments. + - The ref-safe-context contributed by all reference arguments whose corresponding parameters have a ref-safe-context of caller-context. + +2. All `ref` arguments of `ref struct` types shall be assignable by a value with that safe-context. In this rule, `ref` does **not** generalize to include `in` and `out`. + +For any method invocation `e.M(a1, a2, ... aN)`: -In addition the safe-context is the smallest of the safe-contexts of all arguments and operands of all object initializer expressions, recursively, if any initializer is present. +1. Calculate the narrowest safe-context from: + - caller-context. + - The safe-context contributed by all arguments. + - The ref-safe-context contributed by all reference arguments. -> *Note*: These rules rely on `Span` not having a constructor of the following form: +2. All `out` arguments of `ref struct` types shall be assignable by a value with that safe-context. + +The `scoped` modifier restricts the contributions in (1) as specified in [§9.7.2.6](variables.md#9726-function-invocation). + +> *Example*: The following illustrates how the method-arguments-must-match rule prevents a value with a narrower safe-context from being stored into a `ref` argument with a wider safe-context: +> +> +> ```csharp +> ref struct R { } +> +> class C +> { +> static void F0(ref R a, scoped ref R b) { } +> +> static void F1(ref R x, scoped R y) +> { +> // Error: The narrowest safe-context is function-member (from `y`) +> // but `x` is a ref argument of a ref struct type whose +> // safe-context is caller-context. It must be assignable by +> // a value with that narrowest safe-context, which fails. +> F0(ref x, ref y); +> } +> } +> ``` +> +> *end example* + +#### §declaration-expression-safe-context Infer safe-context of declaration expressions + +The safe-context of a declaration variable explicitly declared `scoped` is declaration-block. Otherwise, for a declaration variable from an `out` argument (`M(x, out var y)`) or deconstruction (`(var x, var y) = M()`), it is the narrowest of the following: + +- caller-context. +- If the out variable's type is a `ref struct`, consider all arguments to the containing invocation, including the receiver: + - The safe-context contributed by any argument where its corresponding parameter has safe-context of return-only or wider. + - The ref-safe-context contributed by any argument where its corresponding parameter has ref-safe-context of return-only or wider. + +> *Example*: The following illustrates how the safe-context of an `out` declaration variable is inferred from the other arguments to the invocation: > +> > ```csharp -> public Span(ref T p) +> ref struct RS +> { +> public RS(ref int x) { } +> +> static void M0(RS input, out RS output) => output = input; +> +> static RS M1() +> { +> var i = 0; +> var rs1 = new RS(ref i); // safe-context of rs1 is function-member +> M0(rs1, out var rs2); // safe-context of rs2 is function-member +> return rs2; // Error: rs2 cannot escape function-member +> } +> +> static void M2(RS rs1) +> { +> M0(rs1, out scoped var rs2); // scoped forces safe-context to +> // declaration-block +> } +> } > ``` > -> Such a constructor makes instances of `Span` used as fields indistinguishable from a `ref` field. The safety rules described in this document depend on `ref` fields not being a valid construct in C# or .NET. *end note* +> In `M1`, the safe-context of `rs2` is the narrowest of *caller-context* and the safe-context of `rs1` (*function-member*), which is *function-member*. Therefore `rs2` cannot be returned. In `M2`, the `scoped` modifier forces the safe-context of `rs2` to *declaration-block*. +> +> *end example* + +#### §object-initializer-safe-context Object initializer safe context + +The safe-context of an object initializer expression is the narrowest of: + +1. The safe-context of the constructor invocation. +2. The safe-context and ref-safe-context of arguments to member initializer indexers that can escape to the receiver. +3. The safe-context of the RHS of assignments in member initializers to non-readonly setters, or the ref-safe-context in the case of ref assignment. + +> *Note*: Another way of modeling this is to consider any argument to a member initializer that can be assigned to the receiver as being an argument to the constructor. *end note* + + + +> *Example*: The following illustrates how an object initializer narrows the safe-context of the resulting value: +> +> +> ```csharp +> using System; +> +> ref struct S +> { +> public Span Field; +> public S(ref int i) { } +> } +> +> class C +> { +> static S Example() +> { +> Span stackSpan = stackalloc int[42]; +> int i = 0; +> +> // safe-context is narrowest of: +> // constructor safe-context (caller-context) and +> // RHS of Field assignment (stackSpan: function-member) +> // = function-member +> var x = new S(ref i) { Field = stackSpan }; +> return x; // Error: x has safe-context of function-member +> } +> } +> ``` +> +> *end example* + +#### 16.6.15.7 stackalloc + +The result of a stackalloc expression has safe-context of function-member. + +#### 16.6.15.8 Constructor invocations + +A `new` expression that invokes a constructor obeys the same rules as a method invocation that is considered to return the type being constructed. + +If an object initializer is present, the resulting safe-context is determined by §object-initializer-safe-context. diff --git a/standard/types.md b/standard/types.md index 5e158def1..b2d6f23af 100644 --- a/standard/types.md +++ b/standard/types.md @@ -246,7 +246,7 @@ Every value type has a ***default value***, which is independent of any explicit - For `decimal`, the default value is `0m` (that is, value zero with scale 0). - For `bool`, the default value is `false`. - For an *enum_type* `E`, the default value is `0`, converted to the type `E`. -- For a *struct_type*, the default value is the value produced by setting all value type fields to their default value and all reference type fields to `null`. +- For a *struct_type*, the default value is the value produced by setting all instance fields to their default values ([§9.3](variables.md#93-default-values)), including null references for fields that are reference variables. - For a *nullable_value_type* the default value is an instance for which the `HasValue` property is false. The default value is also known as the ***null value*** of the nullable value type. Attempting to read the `Value` property of such a value causes an exception of type `System.InvalidOperationException` to be thrown ([§8.3.12](types.md#8312-nullable-value-types)). All value types have a public parameterless instance constructor. For a value type that does not explicitly declare one, an implicit parameterless instance constructor, called the ***default constructor***, produces the default value and does not execute instance field initializers. An explicitly declared parameterless instance constructor is not required to produce the default value. @@ -883,11 +883,11 @@ unmanaged_type ; ``` -An *unmanaged_type* is any type that is neither a *reference_type* nor a *type_parameter* that is not constrained to be unmanaged, and contains no instance fields whose type is not an *unmanaged_type*. In other words, an *unmanaged_type* is one of the following: +An *unmanaged_type* is any type that is neither a *reference_type* nor a *type_parameter* that is not constrained to be unmanaged, and contains neither instance fields that are reference variables nor instance fields whose type is not an *unmanaged_type*. In other words, an *unmanaged_type* is one of the following: - `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `nint`, `nuint`, `long`, `ulong`, `char`, `float`, `double`, `decimal`, or `bool`. - Any *enum_type*. -- Any user-defined *struct_type* that contains instance fields of *unmanaged_type*s only. +- Any user-defined *struct_type* that contains instance fields of *unmanaged_type*s only, none of which are reference variables. - Any type parameter which is constrained to be unmanaged. - Any *pointer_type* ([§24.3](unsafe-code.md#243-pointer-types)). diff --git a/standard/unsafe-code.md b/standard/unsafe-code.md index a69ee7d52..a6565fabd 100644 --- a/standard/unsafe-code.md +++ b/standard/unsafe-code.md @@ -133,9 +133,9 @@ The type of the target of a pointer type is called the ***referent type*** of th A *pointer_type* may only be used in an *array_type* in an unsafe context ([§24.2](unsafe-code.md#242-unsafe-contexts)). A *non_array_type* is any type that is not itself an *array_type*. -Unlike references (values of reference types), pointers are not tracked by the garbage collector—the garbage collector has no knowledge of pointers and the data or static methods to which they point. For this reason a pointer is not permitted to point to a reference or to a struct that contains references, and the referent type of a pointer shall be an *unmanaged_type*. Pointer types themselves are unmanaged types, so a pointer type may be used as the referent type for another pointer type. +Unlike references (values of reference types), pointers are not tracked by the garbage collector—the garbage collector has no knowledge of pointers and the data or static methods to which they point. For this reason the referent type of a pointer shall be an *unmanaged_type*. An implementation may permit a managed type as a referent type, in which case a warning is produced. Pointer types themselves are unmanaged types, so a pointer type may be used as the referent type for another pointer type. -The intuitive rule for mixing pointers and references is that referents of references (objects) are permitted to contain pointers, but referents of pointers are not permitted to contain references. +Except where an implementation permits managed referent types as described above, the intuitive rule for mixing pointers and references is that referents of references (objects) are permitted to contain pointers, but referents of pointers are not permitted to contain references. For a given implementation, all pointer types shall have the same size and representation. A null pointer value shall be represented by all-bits-zero. @@ -189,7 +189,7 @@ dataptr_type ; ``` -A *dataptr_type* is written as an *unmanaged_type* ([§8.8](types.md#88-unmanaged-types)), *funcptr_type*, or *voidptr_type*, followed by one or more `*` tokens. +A *dataptr_type* is written as an *unmanaged_type* ([§8.8](types.md#88-unmanaged-types)), *funcptr_type*, or *voidptr_type*, followed by one or more `*` tokens. An implementation that permits managed referent types may also permit a managed type before the `*` tokens, as described above. > *Example*: Some examples of data pointer types are given in the table below: > @@ -708,7 +708,7 @@ addressof_expression *unary_expression* shall designate either a variable or a method group. The variable case is described immediately below. -Given an expression `E` which is of a type `T` and is classified as a fixed variable ([§24.4](unsafe-code.md#244-fixed-and-moveable-variables)), the construct `&E` computes the address of the variable given by `E`. The type of the result is `T*` and is classified as a value. A compile-time error occurs if `E` is not classified as a variable, if `E` is classified as a read-only local variable, or if `E` denotes a moveable variable. In the last case, a fixed statement ([§24.7](unsafe-code.md#247-the-fixed-statement)) can be used to temporarily “fix” the variable before obtaining its address. +Given an expression `E` which is of a type `T` and is classified as a fixed variable ([§24.4](unsafe-code.md#244-fixed-and-moveable-variables)), the construct `&E` computes the address of the variable given by `E`. The type of the result is `T*` and is classified as a value. If `T` is a managed type, a warning is produced. A compile-time error occurs if `E` is not classified as a variable, if `E` is classified as a read-only local variable, or if `E` denotes a moveable variable. In the last case, a fixed statement ([§24.7](unsafe-code.md#247-the-fixed-statement)) can be used to temporarily “fix” the variable before obtaining its address. > *Note*: As stated in [§12.8.7](expressions.md#1287-member-access), outside an instance constructor or static constructor for a struct or class that defines a `readonly` field, that field is considered a value, not a variable. As such, its address cannot be taken. Similarly, the address of a constant cannot be taken. *end note* @@ -891,10 +891,10 @@ Each *fixed_pointer_declarator* declares a local variable of the given *pointer_ It is an error to use a captured local variable ([§12.22.6.2](expressions.md#122262-captured-outer-variables)), value parameter, or parameter array in a *fixed_pointer_initializer*. A *fixed_pointer_initializer* can be one of the following: -- The token “`&`” followed by a *variable_reference* ([§9.5](variables.md#95-variable-references)) to a moveable variable ([§24.4](unsafe-code.md#244-fixed-and-moveable-variables)) of an unmanaged type `T`, provided the type `T*` is implicitly convertible to the pointer type given in the `fixed` statement. In this case, the initializer computes the address of the given variable, and the variable is guaranteed to remain at a fixed address for the duration of the fixed statement. -- An expression of an *array_type* with elements of an unmanaged type `T`, provided the type `T*` is implicitly convertible to the pointer type given in the fixed statement. In this case, the initializer computes the address of the first element in the array, and the entire array is guaranteed to remain at a fixed address for the duration of the `fixed` statement. If the array expression is `null` or if the array has zero elements, the initializer computes an address equal to zero. +- The token “`&`” followed by a *variable_reference* ([§9.5](variables.md#95-variable-references)) to a moveable variable ([§24.4](unsafe-code.md#244-fixed-and-moveable-variables)) of a type `T`, provided the type `T*` is implicitly convertible to the pointer type given in the `fixed` statement. In this case, the initializer computes the address of the given variable, and the variable is guaranteed to remain at a fixed address for the duration of the fixed statement. If `T` is a managed type, a warning is produced. +- An expression of an *array_type* with elements of a type `T`, provided the type `T*` is implicitly convertible to the pointer type given in the fixed statement. In this case, the initializer computes the address of the first element in the array, and the entire array is guaranteed to remain at a fixed address for the duration of the `fixed` statement. If the array expression is `null` or if the array has zero elements, the initializer computes an address equal to zero. If `T` is a managed type, a warning is produced. - An expression of type `string`, provided the type `char*` is implicitly convertible to the pointer type given in the `fixed` statement. In this case, the initializer computes the address of the first character in the string, and the entire string is guaranteed to remain at a fixed address for the duration of the `fixed` statement. The behavior of the `fixed` statement is implementation-defined if the string expression is `null`. -- An expression of type other than *array_type* or `string`, provided there exists an accessible method or accessible extension method matching the signature `ref [readonly] T GetPinnableReference()`, where `T` is an *unmanaged_type*, and `T*` is implicitly convertible to the pointer type given in the `fixed` statement. In this case, the initializer computes the address of the returned variable, and that variable is guaranteed to remain at a fixed address for the duration of the `fixed` statement. A `GetPinnableReference()` method can be used by the `fixed` statement when overload resolution ([§12.6.4](expressions.md#1264-overload-resolution)) produces exactly one function member and that function member satisfies the preceding conditions. The `GetPinnableReference` method should return a reference to an address equal to zero, such as that returned from `System.Runtime.CompilerServices.Unsafe.NullRef()` when there is no data to pin. +- An expression of type other than *array_type* or `string`, provided there exists an accessible method or accessible extension method matching the signature `ref [readonly] T GetPinnableReference()`, where `T*` is a permitted pointer type ([§24.3](unsafe-code.md#243-pointer-types)) implicitly convertible to the pointer type given in the `fixed` statement. In this case, the initializer computes the address of the returned variable, and that variable is guaranteed to remain at a fixed address for the duration of the `fixed` statement. A `GetPinnableReference()` method can be used by the `fixed` statement when overload resolution ([§12.6.4](expressions.md#1264-overload-resolution)) produces exactly one function member and that function member satisfies the preceding conditions. The `GetPinnableReference` method should return a reference to an address equal to zero, such as that returned from `System.Runtime.CompilerServices.Unsafe.NullRef()` when there is no data to pin. If `T` is a managed type, a warning is produced. - A *simple_name* or *member_access* that references a fixed-size buffer member of a moveable variable, provided the type of the fixed-size buffer member is implicitly convertible to the pointer type given in the `fixed` statement. In this case, the initializer computes a pointer to the first element of the fixed-size buffer ([§24.8.3](unsafe-code.md#2483-fixed-size-buffers-in-expressions)), and the fixed-size buffer is guaranteed to remain at a fixed address for the duration of the `fixed` statement. For each address computed by a *fixed_pointer_initializer* the `fixed` statement ensures that the variable referenced by the address is not subject to relocation or disposal by the garbage collector for the duration of the `fixed` statement. diff --git a/standard/variables.md b/standard/variables.md index ba81de4e4..07e8fefd5 100644 --- a/standard/variables.md +++ b/standard/variables.md @@ -190,15 +190,21 @@ A discard introduced by a declaration expression is not initially assigned, so i The following categories of variables are automatically initialized to their default values: - Static variables. -- Instance variables of class instances. +- Instance variables of class and struct instances. - Array elements. The default value of a variable depends on the type of the variable and is determined as follows: - For a variable of a *value_type*, the default value is the default value of that type ([§8.3.3](types.md#833-default-constructors)), without invoking an explicitly declared instance constructor. -- For a variable of a *reference_type*, the default value is `null`. +- For a variable of a *reference_type* or a reference variable, the default value is `null`. + +Reading or writing the referent of a reference variable whose stored reference is null throws `System.NullReferenceException`. > *Note*: Initialization to default values is typically done by having the memory manager or garbage collector initialize memory to all-bits-zero before it is allocated for use. For this reason, it is convenient to use all-bits-zero to represent the null reference. *end note* + + + +> *Note*: To test if a ref variable has been assigned a referent, call `System.Runtime.CompilerServices.Unsafe.IsNullRef(ref fieldName)`. One cannot test a ref variable to see if it has been assigned a referent by using `fieldName == null`, as that tests the value of the (potentially non-existent) referent, not the reference itself. *end note* ## 9.4 Definite assignment @@ -1208,7 +1214,7 @@ Reads and writes of the following data types shall be atomic: `bool`, `char`, `b ### 9.7.1 General -A ***reference variable*** is a variable that refers to another variable, called the referent ([§9.2.6](variables.md#926-reference-parameters)). A reference variable is a local variable declared with the `ref` modifier. +A ***reference variable*** is a variable that refers to another variable, called the referent ([§9.2.6](variables.md#926-reference-parameters)). A reference variable is a local variable or ref struct field declared with the `ref` modifier. A reference variable stores a *variable_reference* ([§9.5](variables.md#95-variable-references)) to its referent and not the value of its referent. When a reference variable is used where a value is required its referent’s value is returned; similarly when a reference variable is the target of an assignment it is the referent which is assigned to. The variable to which a reference variable refers, i.e. the stored *variable_reference* for its referent, can be changed using a ref assignment (`= ref`). @@ -1257,13 +1263,17 @@ A ***reference return*** is the *variable_reference* returned from a return-by-r All reference variables obey safety rules that ensure the ref-safe-context of the reference variable is not greater than the ref-safe-context of its referent. +Ref-safety behavior across module boundaries involving different versions of C# is undefined. + > *Note*: The related notion of a *safe-context* is defined in ([§16.6.15](structs.md#16615-safe-context-constraint)), along with associated constraints. *end note* For any variable, the ***ref-safe-context*** of that variable is the context where a *variable_reference* ([§9.5](variables.md#95-variable-references)) to that variable is valid. The referent of a reference variable shall have a ref-safe-context that is at least as wide as the ref-safe-context of the reference variable itself. > *Note*: A compiler determines the ref-safe-context through a static analysis of the program text. The ref-safe-context reflects the lifetime of a variable at runtime. *end note* -There are three ref-safe-contexts: +The classifications below are subject to the local and parameter rules in [§9.7.2.2](variables.md#9722-local-variable-ref-safe-context) and [§9.7.2.3](variables.md#9723-parameter-ref-safe-context), including explicit `scoped` modifiers and applicable `[UnscopedRef]` attributes. + +There are four ref-safe-contexts: - ***declaration-block***: The ref-safe-context of a *variable_reference* to a local variable ([§9.2.9.1](variables.md#9291-general)) is that local variable’s scope ([§13.6.2](statements.md#1362-local-variable-declarations)), including any nested *embedded-statement*s in that scope. @@ -1271,14 +1281,21 @@ There are three ref-safe-contexts: - ***function-member***: Within a function a *variable_reference* to any of the following has a ref-safe-context of function-member: - - Value parameters ([§15.6.2.2](classes.md#15622-value-parameters)) on a function member declaration, including the implicit `this` of class member functions; and - - The implicit reference (`ref`) parameter ([§15.6.2.3.3](classes.md#156233-reference-parameters)) `this` of a struct member function, along with its fields. + - Value parameters ([§15.6.2.2](classes.md#15622-value-parameters)) on a function member declaration, including the implicit `this` of class member functions; + - Output parameters ([§15.6.2.3.4](classes.md#156234-output-parameters)), which are implicitly `scoped ref`; and + - The implicit reference (`ref`) parameter ([§15.6.2.3.3](classes.md#156233-reference-parameters)) `this` of a struct member function, which is implicitly `scoped ref`, along with its fields. + + A *variable_reference* with ref-safe-context of function-member is a valid referent only if the reference variable is declared in the same function member. + +- ***return-only***: Within a function a *variable_reference* to any of the following has a ref-safe-context of return-only: - A *variable_reference* with ref-safe-context of function-member is a valid referent only if the reference variable is declared in the same function member. + - Reference parameters ([§9.2.6](variables.md#926-reference-parameters)) other than the implicit `this` of a struct member function and other than output parameters; and + - Input parameters ([§15.6.2.3.2](classes.md#156232-input-parameters)). -- ***caller-context***: Within a function a *variable_reference* to any of the following has a ref-safe-context of caller-context: - - Reference parameters ([§9.2.6](variables.md#926-reference-parameters)) other than the implicit `this` of a struct member function; - - Member fields and elements of such parameters; + A *variable_reference* with ref-safe-context of return-only can be the referent of a reference return. + +- ***caller-context***: Within a function a *variable_reference* to any of the following has a ref-safe-context of caller-context: + - Member fields and elements of reference or input parameters; - Member fields of parameters of class type; and - Elements of parameters of array type. @@ -1296,7 +1313,7 @@ These values form a nesting relationship from narrowest (declaration-block) to w > // ref safe context of arr[i] is "caller-context". > private int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; > -> // ref safe context is "caller-context" +> // ref safe context is "return-only" > public ref int M1(ref int r1) > { > return ref r1; // r1 is safe to ref return @@ -1363,43 +1380,97 @@ These values form a nesting relationship from narrowest (declaration-block) to w > > *end example.* +A reference variable that is a local variable or parameter can be scoped explicitly; see §scoped-modifier. + #### 9.7.2.2 Local variable ref safe context For a local variable `v`: -- If `v` is a reference variable, its ref-safe-context is the same as the ref-safe-context of its initializing expression. +- If `v` is a reference variable explicitly declared `scoped`, its ref-safe-context is declaration-block. +- Otherwise, if `v` is a reference variable, its ref-safe-context is the same as the ref-safe-context of its initializing expression. - Otherwise its ref-safe-context is declaration-block. #### 9.7.2.3 Parameter ref safe context -For a parameter `p`: +For a parameter `p`, an explicit `scoped` modifier takes precedence over the defaults below. It gives a reference, input, or output parameter a ref-safe-context of function-member. An applicable `[UnscopedRef]` attribute instead determines the ref-safe-context according to the table in [§UnscopedRefAttribute](attributes.md#unscopedrefattribute-the-unscopedref-attribute). Otherwise: -- If `p` is a reference or input parameter, its ref-safe-context is the caller-context. If `p` is an input parameter, it cannot be returned as a writable `ref` but can be returned as `ref readonly`. -- If `p` is an output parameter, its ref-safe-context is the caller-context. -- Otherwise, if `p` is the `this` parameter of a struct type, its ref-safe-context is the function-member. +- If `p` is the `this` parameter of a struct instance member, its ref-safe-context is function-member. This parameter is implicitly `scoped ref`. +- If `p` is a reference or input parameter, its ref-safe-context is return-only. If `p` is an input parameter, it cannot be returned as a writable `ref` but can be returned as `ref readonly`. +- If `p` is an output parameter, its ref-safe-context is function-member. An output parameter is implicitly `scoped ref`. - Otherwise, the parameter is a value parameter, and its ref-safe-context is the function-member. +> *Example*: The following illustrates how the implicit `this` parameter of a struct instance method is `scoped ref` (ref-safe-context of *function-member*), and how `[UnscopedRef]` widens it to *return-only*, enabling ref returns of fields: +> +> +> ```csharp +> using System.Diagnostics.CodeAnalysis; +> +> struct S +> { +> private int _field; +> +> // Error: ref-safe-context of `this` is function-member, +> // so ref-safe-context of `_field` is also function-member, +> // which does not satisfy the return-only requirement. +> public ref int Bad() => ref _field; +> +> // OK: [UnscopedRef] widens `this` from function-member to +> // return-only, so `_field` also has ref-safe-context of +> // return-only, satisfying the ref return requirement. +> [UnscopedRef] +> public ref int Good() => ref _field; +> } +> ``` +> +> *end example* + #### 9.7.2.4 Field ref safe context For a variable designating a reference to a field, `e.F`: -- If `e` is of a reference type, its ref-safe-context is the caller-context. +- If `F` is a reference variable, its ref-safe-context is the safe-context of `e`. +- Else if `e` is of a reference type, its ref-safe-context is the caller-context. - Otherwise, if `e` is of a value type, its ref-safe-context is the same as the ref-safe-context of `e`. +As a result, a field that is a reference variable may be returned as a reference variable from a `ref struct` or `readonly ref struct`, but a non-reference variable field may not. + +> *Example*: +> +> +> ```csharp +> ref struct RS +> { +> ref int _refField; +> int _field; +> public ref int Prop1 => ref _refField; // OK +> public ref int Prop2 => ref _field; // Error +> } +> ``` +> +> *end example* + #### 9.7.2.5 Operators The conditional operator ([§12.21](expressions.md#1221-conditional-operator)), `c ? ref e1 : ref e2`, and reference assignment operator, `= ref e` ([§12.24.1](expressions.md#12241-general)) have reference variables as operands and yield a reference variable. For those operators, the ref-safe-context of the result is the narrowest context among the ref-safe-contexts of all `ref` operands. #### 9.7.2.6 Function invocation -For a variable `c` resulting from a ref-returning function invocation, its ref-safe-context is the narrowest of the following contexts: +For these invocation rules, including the method-arguments-must-match and declaration-expression inference rules, a reference argument includes an argument corresponding to an `in` parameter or an `[UnscopedRef] out` parameter, except where a rule explicitly distinguishes parameter-passing modes. For an input argument that is a *variable_reference*, its ref-safe-context is that of the variable; otherwise it is function-member. + +An argument, including the receiver, contributes contexts as follows: + +- It contributes safe-context if its corresponding parameter is not an output parameter and is not a value parameter declared `scoped`. In particular, `scoped ref` and `scoped in` do not suppress safe-context contribution. +- It contributes ref-safe-context if its corresponding parameter is a reference or input parameter not declared `scoped`, or is an output parameter annotated `[UnscopedRef]`. An ordinary output parameter and the implicitly scoped `this` parameter of a struct do not contribute ref-safe-context. + +For a variable `c` resulting from a ref-returning function invocation, `ref e1.M(e2, ...)`, where `M()` does not return ref-to-ref-struct, its ref-safe-context is the narrowest of the following contexts: - The caller-context. -- The ref-safe-context of all `ref`, `out`, and `in` argument expressions (excluding the receiver). -- For each input parameter, if there is a corresponding expression that is a variable and there exists an identity conversion between the type of the variable and the type of the parameter, the variable’s ref-safe-context, otherwise the nearest enclosing context. -- The safe-context ([§16.6.15](structs.md#16615-safe-context-constraint)) of all argument expressions (including the receiver). +- The safe-context ([§16.6.15](structs.md#16615-safe-context-constraint)) contributed by all argument expressions. +- The ref-safe-context contributed by all reference arguments. + +If `M()` does return ref-to-ref-struct, the ref-safe-context is the narrowest ref-safe-context contributed by all arguments which are ref-to-ref-struct. -> *Example*: the last bullet is necessary to handle code such as +> *Example*: A reference argument can restrict the ref-safe-context of a result: > > > ```csharp @@ -1438,4 +1509,121 @@ A `new` expression that invokes a constructor obeys the same rules as a method i - Neither a reference parameter, nor an output parameter, nor an input parameter, nor a parameter of a `ref struct` type shall be an argument for an iterator method or an `async` method. - Neither a `ref` local, nor a local of a `ref struct` type shall be in context at the point of a `yield return` statement or an `await` expression. - For a ref reassignment `e1 = ref e2`, the ref-safe-context of `e2` shall be at least as wide a context as the *ref-safe-context* of `e1`. -- For a ref return statement `return ref e1`, the ref-safe-context of `e1` shall be the caller-context. +- For a ref return statement `return ref e1`, the ref-safe-context of `e1` shall be at least return-only. + +### §scoped-modifier The scoped modifier + +The contextual keyword `scoped` is used as a modifier to restrict the ref-safe-context ([§9.7.2](variables.md#972-ref-safe-contexts)) or safe-context ([§16.6.15](structs.md#16615-safe-context-constraint)) of a variable. The presence of this modifier requires that related code doesn’t extend the lifetime of the variable. + +`scoped` shall only be applied to reference variables (which includes non-value parameters) and to variables of a ref struct type. `scoped` shall not be applied to fields, array elements, or return types. + +The effect on ref-safe-context is specified in [§9.7.2.2](variables.md#9722-local-variable-ref-safe-context) and [§9.7.2.3](variables.md#9723-parameter-ref-safe-context). The effect on safe-context is specified in [§16.6.15.2](structs.md#166152-parameter-safe-context) and [§16.6.15.3](structs.md#166153-local-variable-safe-context). These rules take precedence over initializer and default-context inference. + +The following table illustrates local declarations whose initializers have caller-context for both safe-context and, where applicable, ref-safe-context: + +| Local Variable | ref-safe-context | safe-context | +|---|---|---| +| `Span s` | *declaration-block* | *caller-context* | +| `scoped Span s` | *declaration-block* | *declaration-block* | +| `ref Span s` | *caller-context* | *caller-context* | +| `scoped ref Span s` | *declaration-block* | *caller-context* | + +In this relationship the *ref-safe-context* of a value can never be wider than the *safe-context*. + +> *Example*: The following illustrates how `scoped` restricts the lifetime of a local and prevents it from escaping its enclosing function: +> +> +> ```csharp +> using System; +> +> class C +> { +> static Span Bad() +> { +> // Without `scoped`, the safe-context of `s` would be caller-context +> // because the right-hand side has safe-context of caller-context. +> // The `scoped` modifier forces the safe-context to function-member, +> // so `s` cannot be returned. +> scoped Span s = default; +> return s; // Error: s has safe-context of function-member +> } +> } +> ``` +> +> *end example* + + + +> *Example*: The following illustrates how `scoped ref` on a parameter prevents the parameter from being captured by a constructed `ref struct` value that the method returns: +> +> +> ```csharp +> ref struct RS +> { +> public ref int RefField; +> public RS(ref int i) { RefField = ref i; } +> } +> +> class C +> { +> // `scoped ref` means `value` does not contribute ref-safe-context +> // to the return value. The `RS` constructor requires a ref argument +> // with ref-safe-context of caller-context, but `value` only contributes +> // function-member, so the call is rejected. +> static RS CreateWithoutCapture(scoped ref int value) +> => new RS(ref value); +> } +> ``` +> +> *end example* + +In summary, two `ref` locations are implicitly `scoped`: the `this` parameter of a struct instance method, and every `out` parameter. See §9.7.2.3. + +### §parameter-scope-variance Parameter scope variance + +The `scoped` modifier (§scoped-modifier) and `[UnscopedRef]` attribute (§UnscopedRefAttribute) on parameters affect overriding, interface implementation, and `delegate` conversion. The signature for an override, interface implementation, or `delegate` conversion may: + +- Add `scoped` to a `ref` or `in` parameter. +- Add `scoped` to a parameter of a `ref struct` type. +- Remove `[UnscopedRef]` from an `out` parameter. +- Remove `[UnscopedRef]` from a `ref` parameter of a `ref struct` type. + +Any other difference with respect to `scoped` or `[UnscopedRef]` between the base and the overriding, implementing, or converting signature is a mismatch. + +A mismatch is unsafe when any of the following holds: + +- The mismatch adds `[UnscopedRef]` to a `ref` or `out` parameter of ref struct type. +- The signature returns a ref struct or returns by `ref` or `ref readonly`, and has a `ref`, `in`, or `out` parameter or a value parameter of ref struct type. +- The signature has a `ref` or `out` parameter of ref struct type and at least one other `ref`, `in`, or `out` parameter or value parameter of ref struct type. + +An unsafe mismatch is a compile-time error. Other parameter-scope mismatches do not require a diagnostic. + +The `scoped` modifier and `[UnscopedRef]` attribute do not affect hiding. + +Overloads shall not differ only on `scoped` or `[UnscopedRef]`. + +> *Example*: The following illustrates valid and invalid scope variance in overrides: +> +> +> ```csharp +> using System; +> +> class Base +> { +> public virtual void M(ref Span x) { } +> } +> +> class Derived : Base +> { +> // OK: adds scoped to a ref parameter +> public override void M(scoped ref Span x) { } +> } +> +> class C +> { +> void N(Span x) { } +> void N(scoped Span x) { } // Error: overloads differ only on scoped +> } +> ``` +> +> *end example* diff --git a/tools/example-templates/additional-files/RefStruct.cs b/tools/example-templates/additional-files/RefStruct.cs index 8a1de6823..168251305 100644 --- a/tools/example-templates/additional-files/RefStruct.cs +++ b/tools/example-templates/additional-files/RefStruct.cs @@ -1 +1,5 @@ -public ref struct RS {} +ref struct RS +{ + public ref int Field; + public RS(ref int i) { Field = ref i; } +}