diff --git a/standard/attributes.md b/standard/attributes.md index 89f8822d9..fe98d9c4b 100644 --- a/standard/attributes.md +++ b/standard/attributes.md @@ -512,6 +512,7 @@ A number of attributes affect the language in some way. These attributes include - `System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute` and `System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute`, which are used to declare a custom interpolated string expression handler ([§23.5.11.1](attributes.md#235111-custom-interpolated-string-expression-handlers)) and to call one of its constructors, respectively. - System.Diagnostics.CodeAnalysis.UnscopedRefAttribute ([§23.5.8](attributes.md#2358-the-unscopedref-attribute)), which allows an otherwise implicitly scoped ref to be treated as not being scoped. - `System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute` ([§23.5.12.1](attributes.md#235121-the-setsrequiredmembers-attribute)) and `System.Runtime.CompilerServices.RequiredMemberAttribute` ([§23.5.12.2](attributes.md#235122-the-requiredmember-attribute)), which are used in required-member contexts ([§15.7.1](classes.md#1571-general)). +- `System.Runtime.CompilerServices.InlineArrayAttribute` (§InlineArrayAttribute), which marks a struct type as an inline array type (§InlineArray). 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)). @@ -1739,6 +1740,10 @@ This attribute indicates that the constructor it decorates sets all required mem This attribute indicates that the current type has one or more required members ([§15.7.1](classes.md#1571-general)), or that a specific member of that type is required. However, it is an error for this attribute to be used explicitly. Instead, the presence of the modifier `required` results in the type or member being treated as if it were decorated with this attribute. +### §InlineArrayAttribute The InlineArray attribute + +This attribute is used to identify a struct type as an inline array type. The declaration conditions, including the restriction on `record struct` declarations, are specified in §InlineArray. + ## 23.6 Attributes for interoperation For interoperation with other languages, an indexer may be implemented using indexed properties. If the indexer is not decorated with `IndexerNameAttribute`, then the name `Item` is used by default. `IndexerNameAttribute` enables a developer to override this default and specify a different name. diff --git a/standard/conversions.md b/standard/conversions.md index 345c7bd8e..839ca8f49 100644 --- a/standard/conversions.md +++ b/standard/conversions.md @@ -481,6 +481,25 @@ A warning shall be issued for an implicit conversion of a method group to `objec > > *end example* +### §ImplicitInlineArrayConversions Implicit inline array conversions + +The implicit inline array (§InlineArray) conversions are: + +- From an expression designating a writable inline array variable with element type `T` to `System.Span`. +- From an expression designating a writable inline array variable with element type `T` to `System.ReadOnlySpan`. +- From an expression designating a readonly inline array variable with element type `T` to `System.ReadOnlySpan`. + +The resulting span contains all elements of the designated inline array, in order, and refers to its storage. For ref-safety analysis, the safe-context of the conversion is that of a method invocation ([§16.6.15.6](structs.md#166156-method-and-property-invocation)) with the corresponding signature: + +```csharp +static System.Span Convert(ref «InlineArrayType» array) +static System.ReadOnlySpan Convert(in «InlineArrayType» array) +``` + +The modeled invocation passes the designated variable as a reference argument for `System.Span`, or as an input argument for `System.ReadOnlySpan`. The actual storage's ref-safe-context contributes to the resulting span's safe-context, together with the safe-context of the argument, under the invocation rules. In particular, a conversion does not extend the lifetime of local or temporary storage. These signatures specify the conversion's ref-safety semantics, not a requirement to declare or invoke such methods. + +The conversion of an inline array to `System.Span` or `System.ReadOnlySpan` ignores any declared operators in the inline array type that might otherwise appear to be applicable. See §InlineArray for more information. + ## 10.3 Explicit conversions ### 10.3.1 General @@ -725,6 +744,7 @@ The following implicit conversions are classified as standard implicit conversio - Boxing conversions ([§10.2.9](conversions.md#1029-boxing-conversions)) - Implicit constant expression conversions ([§10.2.11](conversions.md#10211-implicit-constant-expression-conversions)) - Implicit conversions involving type parameters ([§10.2.12](conversions.md#10212-implicit-conversions-involving-type-parameters)) +- Implicit inline array conversions (§ImplicitInlineArrayConversions) The standard implicit conversions specifically exclude user-defined implicit conversions. diff --git a/standard/expressions.md b/standard/expressions.md index fc6f7f8ee..f6595707d 100644 --- a/standard/expressions.md +++ b/standard/expressions.md @@ -2485,9 +2485,9 @@ The *primary_expression* of an *element_access* shall not be an *array_creation_ An *element_access* is dynamically bound ([§12.3.3](expressions.md#1233-dynamic-binding)) if at least one of the following holds: - The *primary_expression* has compile-time type `dynamic`. -- At least one expression of the *argument_list* has compile-time type `dynamic`. +- At least one expression of the *argument_list* has compile-time type `dynamic`, and either the *primary_expression* does not have an inline array type (§InlineArray) or there is more than one *argument* in the *argument_list*. -In this case the compile-time type of the *element_access* depends on the compile-time type of its *primary_expression*: if it has an array type then the compile-time type is the element type of that array type; otherwise the compile-time type is `dynamic` and the *element_access* is classified as a value of type `dynamic`. The rules below to determine the meaning of the *element_access* are then applied at run-time, using the run-time type instead of the compile-time type of those of the *primary_expression* and *argument_list* expressions which have the compile-time type `dynamic`. If the *primary_expression* does not have compile-time type `dynamic`, then the element access undergoes a limited compile-time check as described in [§12.6.5](expressions.md#1265-compile-time-checking-of-dynamic-member-invocation). +In this case the compile-time type of the *element_access* depends on the compile-time type of its *primary_expression*: if it has an array type then the compile-time type is the element type of that array type; otherwise the compile-time type is `dynamic` and the *element_access* is classified as a value of type `dynamic`. The rules below to determine the meaning of the *element_access* are then applied at run-time, using the run-time type instead of the compile-time type of those of the *primary_expression* and *argument_list* expressions which have the compile-time type `dynamic`, except that a receiver of compile-time type `dynamic` does not select inline array element access. If the *primary_expression* does not have compile-time type `dynamic`, then the element access undergoes a limited compile-time check as described in [§12.6.5](expressions.md#1265-compile-time-checking-of-dynamic-member-invocation). > *Example*: > @@ -2501,14 +2501,19 @@ In this case the compile-time type of the *element_access* depends on the compil > > *end example* -If the *primary_expression* of an *element_access* is: +The meaning of an *element_access* is determined by the following ordered rules: -- a value of an array type, the *element_access* is an array access ([§12.8.12.2](expressions.md#128122-array-access)); -- a value of `string` type, the *element_access* is a string access ([§12.8.12.3](expressions.md#128123-string-access)); -- otherwise, the *primary_expression* shall be a variable or value of a class, struct, or interface type that has one or more indexer members, in which case the *element_access* is an indexer access ([§12.8.12.4](expressions.md#128124-indexer-access)). +- If the *primary_expression* is a value of an array type, the *element_access* is an array access ([§12.8.12.2](expressions.md#128122-array-access)). +- Otherwise, if the *primary_expression* is a value of `string` type, the *element_access* is a string access ([§12.8.12.3](expressions.md#128123-string-access)). +- Otherwise, if the *primary_expression* has compile-time inline array type (§InlineArray) and designates a variable or value, and the *argument_list* consists of a single argument, the *element_access* is an inline array element access (§InlineArrayElementAccess). +- Otherwise, the *primary_expression* shall be a variable or value of a class, struct, or interface type that has one or more indexer members, in which case the *element_access* is an indexer access ([§12.8.12.4](expressions.md#128124-indexer-access)). + +An *initializer_target* of the form `'[' argument_list ']'` in an object initializer ([§12.8.17.2.2](expressions.md#1281722-object-initializers)) uses indexer binding, not inline array element access. A suitable declared indexer of an inline array type can therefore be used in an object initializer. #### 12.8.12.2 Array access +For access to elements in an inline array (§InlineArray) see §InlineArrayElementAccess. + For an array access the *argument_list* shall not contain named arguments or by-reference arguments ([§15.6.2.3](classes.md#15623-by-reference-parameters)). The number of expressions in the *argument_list* shall be the same as the rank of the *array_type*, and each expression shall be: @@ -2542,6 +2547,163 @@ The run-time processing of an array access of the form `P[A]`, where `P` is a *p - The value of each expression in the *argument_list* is checked against the actual bounds of each dimension of the array instance referenced by `P`. If one or more values are out of range, a `System.IndexOutOfRangeException` is thrown and no further steps are executed. - The variable reference of the array element given by the index expressions is computed, and this becomes the result of the array access. +#### §InlineArrayElementAccess Inline array element access + +For access to an element in an inline array (§InlineArray), the *primary_expression* of the *element_access* shall designate an inline array. Furthermore, the *argument_list* shall contain a single unnamed value argument ([§12.6.2.1](expressions.md#12621-general)). That *argument* shall be of type `int`, or be implicitly convertible to type `int`, `System.Index`, or `System.Range`. The first applicable case in the order given below is used. Let `T` be the element type and `L` the declared length of the inline array. + +The receiver is evaluated once, followed by the argument and its applicable conversion, each evaluated once. If any evaluation or conversion throws an exception, no further steps are executed. For a variable receiver, the access uses the designated storage; for a value receiver, it uses the resulting value. + +It is a compile-time error if *argument* is a constant expression whose value results in an index outside the bounds of the inline array. An integer-based index outside the interval from zero through `L - 1` throws a `System.IndexOutOfRangeException` at run-time. Range validation and its exception are specified below. + +**When *argument*’s type is `int`** + +If *primary_expression* is a writable variable, the result of evaluating an inline array element access is a writable variable equivalent to invoking the indexer + +```csharp +public ref T this[int index] { get; } +``` + +with *argument* as the index, on an instance of `System.Span` that was created from the inline array designated by *primary_expression*. For the purpose of ref-safety analysis, the ref-safe-context ([§9.7.2.6](variables.md#9726-function-invocation)) and safe-context ([§16.6.15.6](structs.md#166156-method-and-property-invocation)) of the access are those of an invocation passing the receiver by reference to a method with the signature + +```csharp +static ref T GetItem(ref «InlineArrayType» array) +``` + +The resulting variable is considered movable if and only if *primary_expression* is movable. + +If *primary_expression* is a readonly variable, the result of evaluating an inline array element access is a readonly variable equivalent to invoking the indexer + +```csharp +public ref readonly T this[int index] { get; } +``` + +with *argument* as the index, on an instance of `System.ReadOnlySpan` that was created from the inline array designated by *primary_expression*. For the purpose of ref-safety analysis, the ref-safe-context and safe-context of the access are those of an invocation passing the receiver as an input argument to a method with the signature + +```csharp +static ref readonly T GetItem(in «InlineArrayType» array) +``` + +The resulting variable is considered movable if and only if *primary_expression* is movable. + +If *primary_expression* is a value, the result of evaluating an inline array element access is a value equivalent to invoking the indexer + +```csharp +public ref readonly T this[int index] { get; } +``` + +with *argument* as the index, on an instance of `System.ReadOnlySpan` that was created from the inline array designated by *primary_expression*. For the purpose of ref-safety analysis, the safe-context of the access is that of an invocation passing the receiver by value to a method with the signature + +```csharp +static T GetItem(«InlineArrayType» array) +``` + +> *Example*: +> +> +> ```csharp +> [System.Runtime.CompilerServices.InlineArray(10)] +> public struct Buffer10 +> { +> private T _element0; +> } +> public class Program +> { +> void M1(Buffer10 x) +> { +> ref int a = ref x[0]; // OK +> } +> void M2(in Buffer10 x) +> { +> ref readonly int a = ref x[0]; // OK +> ref int b = ref x[0]; // Error; x is readonly +> } +> Buffer10 GetBuffer() => default; +> void M3() +> { +> int a = GetBuffer()[0]; // OK +> ref readonly int b = ref GetBuffer()[0];// Error, rhs is a value +> ref int c = ref GetBuffer()[0]; // Error; rhs is a value +> } +> } +> ``` +> +> *end example* + +**When *argument*’s type is implicitly convertible to `int`** + +The value of *argument* is converted to `int` and the element access is interpreted as described when *argument*’s type is `int` + +**When *argument*’s type is implicitly convertible to `System.Index`** + +*argument* is converted to `System.Index`. Its offset relative to the start of the inline array is obtained using `GetOffset(L)` ([§18.2](ranges.md#182-the-index-type)). Then, the element access is interpreted as described when *argument*’s type is `int`, using that offset. + +Using an index of `System.Index` to access an element in a non-inline array is described in [§12.8.12.2](expressions.md#128122-array-access). However, note carefully that that process is *not* used when an inline array is indexed using a `System.Index`. Specifically, an inline array element access ignores any declared indexers in the inline array type. See §InlineArray for more information. + +**When *argument*’s type is implicitly convertible to `System.Range`** + +*argument* is converted to `System.Range`. The start offset `S` and end offset `E` are computed from its `Start` and `End` indices using `GetOffset(L)`. If `S` or `E` is outside the interval from zero through `L`, or `E` is less than `S`, a `System.ArgumentOutOfRangeException` is thrown and no further steps are executed. The slice starts at `S` and has length `E - S` ([§18.3](ranges.md#183-the-range-type)). + +If *primary_expression* is a writable variable, the result of evaluating an inline array element access is a value of type `System.Span` equivalent to invoking the method + +```csharp +public System.Span Slice(int start, int length) +``` + +passing `S` and `E - S`, respectively, on an instance of `System.Span` that was created from the inline array designated by *primary_expression*. For the purpose of ref-safety analysis, the safe-context of the access is that of an invocation passing the receiver by reference to a method with the signature + +```csharp +static System.Span GetSlice(ref «InlineArrayType» array) +``` + +If *primary_expression* is a readonly variable, the result of evaluating an inline array element access is a value of type `System.ReadOnlySpan` equivalent to invoking the method + +```csharp +public System.ReadOnlySpan Slice(int start, int length) +``` + +passing `S` and `E - S`, respectively, on an instance of `System.ReadOnlySpan` that was created from the inline array designated by *primary_expression*. For the purpose of ref-safety analysis, the safe-context of the access is that of an invocation passing the receiver as an input argument to a method with the signature + +```csharp +static System.ReadOnlySpan GetSlice(in «InlineArrayType» array) +``` + +Using an index of `System.Range` to access an element in a non-inline array is described in [§12.8.12.2](expressions.md#128122-array-access). However, note carefully that that process is *not* used when an inline array is indexed using a `System.Range`. Specifically, an inline array element access ignores any declared Slice methods in the inline array type. See §InlineArray for more information. + +If *primary_expression* is a value, an error is reported. + +In the modeled invocations for element references and slice values, a by-reference receiver argument contributes the contexts of the actual inline array storage, as for the corresponding implicit inline array conversion (§ImplicitInlineArrayConversions). The signatures specify ref-safety semantics; they do not require methods with these names to be declared or invoked. + +> *Example*: +> +> +> +> ```csharp +> [System.Runtime.CompilerServices.InlineArray(10)] +> public struct Buffer10 +> { +> private T _element0; +> } +> public class Program +> { +> void M1(Buffer10 x) +> { +> System.Span a = x[..]; // OK +> } +> void M2(in Buffer10 x) +> { +> System.ReadOnlySpan a = x[..]; // OK +> System.Span b = x[..]; // Error; no implicit conversion +> } +> Buffer10 GetBuffer() => default; +> void M3() +> { +> _ = GetBuffer()[..]; // Error; rhs is a value +> } +> } +> ``` +> +> *end example* + #### 12.8.12.3 String access For a string access the *argument_list* of the *element_access* shall contain a single unnamed value argument ([§15.6.2.2](classes.md#15622-value-parameters)) which shall be: diff --git a/standard/standard-library.md b/standard/standard-library.md index 947dc6879..40b0f7e9b 100644 --- a/standard/standard-library.md +++ b/standard/standard-library.md @@ -903,6 +903,14 @@ namespace System.Runtime.CompilerServices void UnsafeOnCompleted(Action continuation); } + [AttributeUsage(AttributeTargets.Struct, AllowMultiple=false)] + public sealed class InlineArrayAttribute : Attribute + { + public InlineArrayAttribute(int length); + + public int Length { get; } + } + public interface INotifyCompletion { void OnCompleted(Action continuation); @@ -1537,6 +1545,7 @@ The following library types are referenced in this specification. The full names - `global::System.Runtime.CompilerServices.FormattableStringFactory` - `global::System.Runtime.CompilerServices.ICriticalNotifyCompletion` - `global::System.Runtime.CompilerServices.IndexerNameAttribute` +- `global::System.Runtime.CompilerServices.InlineArrayAttribute` - `global::System.Runtime.CompilerServices.INotifyCompletion` - `global::System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute` - `global::System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute` diff --git a/standard/statements.md b/standard/statements.md index c6a838220..4ab7e3dd9 100644 --- a/standard/statements.md +++ b/standard/statements.md @@ -1205,6 +1205,18 @@ In addition, the following modifications are made to the steps in [§13.9.5.1](s Before the process described in [§13.9.5.1](statements.md#13951-general), the following steps are taken: +- If the type `X` of *expression* is an inline array type (§InlineArray) with element type `U`, the statement is bound and executed as iteration over the following span, before looking up any enumeration pattern or enumerable interface on `X`: + - For a writable variable, a `System.Span` obtained by the implicit inline array conversion (§ImplicitInlineArrayConversions). + - For a readonly variable, a `System.ReadOnlySpan` obtained by that conversion. + - For a value, a `System.ReadOnlySpan` over a copy of the value. The copy has the lifetime of the statement and is not accessible to user code. + + For inline array iteration with a reference iteration variable, *expression* shall designate a variable: a writable variable for `ref` iteration, or a writable or readonly variable for `ref readonly` iteration. + + The remaining binding and execution rules apply to the selected span rather than `X`. The collection type `C` and enumerator type `E` are those of that span. The iteration type is `ref U` for a writable variable, `ref readonly U` for a readonly variable, and `U` for a value; thus the element type of an implicitly typed iteration variable is `U`. The iteration-variable conversion and reference-binding rules below apply. In particular, writable reference iteration accesses the original elements, readonly reference iteration permits only reading them, and value iteration obtains an element value on each iteration. + + The inline array expression is evaluated exactly once, before iteration begins. A variable receiver retains its designated storage, so modifications to its elements can be observed by subsequent iterations. A value receiver is copied once, and iteration uses that copy. Elements are visited in increasing index order from zero through the declared length minus one. The contexts of element references and values are determined by inline array element access (§InlineArrayElementAccess), with references into the value copy limited to its lifetime. + + This semantic equivalence does not require span or enumerator local variables in the generated code. A synchronous value iteration over an inline array can occur in an async method or iterator. The existing restrictions on reference iteration variables in async methods and iterators ([§13.6.2.4](statements.md#13624-explicitly-typed-ref-local-variable-declarations)) still apply, and a reference returned by a call shall not be preserved across an `await` or `yield` boundary. - If the type `X` of *expression* is an array type then there is an implicit reference conversion from `X` to the `IEnumerable` interface where `T` is the element type of the array `X` ([§17.2.3](arrays.md#1723-arrays-and-the-generic-collection-interfaces)). - If the type `X` of *expression* is `dynamic` then there is an implicit conversion from *expression* to the `IEnumerable` interface ([§10.2.10](conversions.md#10210-implicit-dynamic-conversions)). The collection type is the `IEnumerable` interface and the enumerator type is the `IEnumerator` interface. If the `var` identifier is given as the *local_variable_type* then the iteration type is `dynamic`, otherwise it is `object`. diff --git a/standard/structs.md b/standard/structs.md index e0c7fb5f5..de9370d31 100644 --- a/standard/structs.md +++ b/standard/structs.md @@ -481,6 +481,93 @@ constructor declaration. The body of the method assigns each parameter of the De If the instance members accessed in the body do not include a property with a non-`readonly` `get` accessor, then the synthesized `Deconstruct` method is `readonly`. The method can be declared explicitly. It is an error if the explicit declaration does not match the expected signature or accessibility, or is static. +## §InlineArray Inline arrays + +A struct type decorated with the attribute `System.Runtime.CompilerServices.InlineArrayAttribute` (§InlineArrayAttribute) is an ***inline array type***. An instance of that type is an ***inline array***, whose layout repeats the storage of its single instance field to contain a contiguous block of the specified number of elements of that field's type. The first element occupies the same storage as the instance field. Managed and unmanaged classification follows the ordinary rules for struct types ([§8.8](types.md#88-unmanaged-types)). It’s the safe-code equivalent of unsafe-code’s fixed-size buffer ([§24.8](unsafe-code.md#248-fixed-size-buffers)). + +With some limitations (see later below), an inline array can be used like an array ([§17](arrays.md#17-arrays)). + +Consider the following: + + +```csharp +var buffer = new Buffer(); + +for (int i = 0; i < 5; ++i) +{ + buffer[i] = i; +} + +foreach (var i in buffer) +{ + Console.WriteLine(i); +} + +Console.WriteLine($"buffer[^2] = >{buffer[^2]}<"); +Console.WriteLine($"buffer[1..^0][0] = >{buffer[1..^0][0]}<"); + +[System.Runtime.CompilerServices.InlineArray(5)] +public struct Buffer +{ + private int _element0; + // other, optional, non-instance-field members +} +``` + +which produces this output: + +```console +0 +1 +2 +3 +4 +buffer[^2] = >3< +buffer[1..^0][0] = >1< +``` + +The attribute constructor requires a positive-valued `int` argument that indicates the number of elements in each inline array created from this type, in this case, five. The target shall be a struct type declared without `record`, and shall have a layout other than explicit layout (specified by `System.Runtime.InteropServices.StructLayoutAttribute` with `System.Runtime.InteropServices.LayoutKind.Explicit`). The struct type shall have exactly one instance field, whose type becomes that of the inline array’s elements. The accessibility of the instance field has no impact on the program’s ability to access the inline array via its struct-instance name, in this case, `buffer`. + +There are a number of restrictions on the instance field’s declaration: + +- It shall not contain the *field_modifier*s `readonly`, `ref`, `required`, or `volatile`. +- It shall not be declared as a *fixed_size_buffer_declaration* ([§24.8](unsafe-code.md#248-fixed-size-buffers)). +- *type* shall be a type valid as a type argument. + +`buffer` is an instance of `Buffer`, and contains an array of five `int` with element `buffer[0]` occupying the same memory as `buffer._element0`. However, unlike an array type, which has a public `Length` property, `buffer` is not derived from `System.Array`, and has no such member. + +> *Note*: One could add a public `Length` property to `Buffer` (for example, returning the constant `5`). An implementation using `sizeof(Buffer)/sizeof(int)` requires an unsafe context; a `Length` property is not inherently unsafe. Alternatively, one could perform an implicit conversion to `System.Span` or `System.ReadOnlySpan` and use its `Length` property. *end note* + +An inline array can be iterated over by a synchronous `foreach` statement as specified in [§13.9.5.2](statements.md#13952-synchronous-foreach), as shown. + +The elements of the inline array can be accessed for read or write via subscripting (§InlineArrayElementAccess). + +A list pattern ([§11.2.11](patterns.md#11211-list-pattern)) shall not be used in the context of an inline array. + +Any indexers or `Slice` methods declared for an inline array type that have signatures matching those defined for non-inline array processing, shall not be used during inline array element access. +> *Example*: Consider the following: +> +> +> ```csharp +> var buffer = new Buffer(); +> int x = buffer[2]; // element access +> +> [System.Runtime.CompilerServices.InlineArray(5)] +> public struct Buffer +> { +> private int _element0; +> public int this[int index] // NOT USED for element access +> { +> get +> { +> return 0; +> } +> } +> } +> ``` +> +> Even though the struct declares an indexer taking an `int` argument, that indexer is not used by element access `buffer[2]`. *end example* + ## 16.5 Record struct and struct differences A record struct differs from a struct in several important ways: