dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
18.76k stars 3.99k forks source link

Improve experience when using stack-only types in interactive code #40213

Open tmat opened 4 years ago

tmat commented 4 years ago

This doesn't work since script variables are not stack allocated:

> var span = new byte[] { 1, 2, 3 }.AsSpan();
(1,1): error CS8345: Field or auto-implemented property cannot be of type 'Span<byte>' unless it is an instance member of a ref struct.

This is by design, the message could be better though (something like Script variables cannot be of type 'Span<byte>'.).

Similarly for ref locals:

> ref int x;
(1,10): error CS1003: Syntax error, '(' expected
(1,10): error CS1026: ) expected
> 

We should parse the declaration and report semantic error.

This doesn't work since top-level code is implicitly async:

> {
.     var span = new byte[] { 1, 2, 3 }.AsSpan();
. }
(2,5): error CS4012: Parameters or locals of type 'Span<byte>' cannot be declared in async methods or lambda expressions.

Is there a reason why this can't be allowed for variables that do not need to be hoisted? Is it just to simplify handling of these cases?

If we don't make this work we should report a better error message (e.g. Locals of type 'Span<byte>' cannot be declared outside of methods in scripts.).

BTW, one can still work with spans in interactive, they just need to be declared within a method:

> void F()
. {
.     var span = new byte[] { 1, 2, 3 }.AsSpan();
. 
. }
tmat commented 4 years ago

@agocke

Is there a reason why this can't be allowed for variables that do not need to be hoisted?

tmat commented 4 years ago

@MadsTorgersen FYI

tmat commented 3 months ago

Partially addressed by https://github.com/dotnet/roslyn/pull/72664