Nullable annotations shift after an anonymous type: NullableAttribute flags skip the anonymous type's type arguments

Aperta
#4,016 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
74/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Tranquilla
Stack tecnologico
csharp

Direzione di ricerca

Inizia da ApplyAttributeTypeVisitor.cs, in particolare da VisitParameterizedType e ExpectDummyNullabilityForGenericValueType vicino alla riga 240. Esegui il driver fornito su AnonNullableRepro.dll e analizza il campo della lambda memorizzata nella cache e l'output del metodo lambda. Il lavoro è completato quando gli argomenti di tipo anonimo non spostano più i flag NullableAttribute successivi e il comportamento correlato di DynamicAttribute e TupleElementNamesAttribute è stato verificato.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Whenever a signature contains an anonymous type, every nullable annotation after it lands on the wrong type argument. NullableAttribute's flag array has no entry for an anonymous type's type arguments, but ApplyAttributeTypeVisitor walks them and consumes a flag for each, so the rest of the type is read from the flag stream at the wrong index.

This is a Release-mode output bug, not just the Debug.Assert mentioned at the end.

Repro

Repro.cs, compiled as a net9.0 library with <Nullable>enable</Nullable> (Release):

using System;
using System.Collections.Generic;
using System.Linq;

public class Repro
{
	public void M(IEnumerable<string> xs)
	{
		xs.Select(x => new { A = x, B = x }).Pick(a => new List<string?>());
	}
}

public static class Ext
{
	public static IEnumerable<T> Pick<TSource, T>(this IEnumerable<TSource> source,
		Func<TSource, List<T?>> selector) where T : class => throw new NotSupportedException();
}

csc caches the second lambda in

.field public static class [System.Runtime]System.Func`2<class '<>f__AnonymousType0`2'<string,string>,
                                                        class [System.Collections]System.Collections.Generic.List`1<string>> '<>9__0_1'
  .custom instance void ...NullableAttribute::.ctor(uint8[]) = ( 01 00 04 00 00 00 00 00 01 02 00 00 )

That is 4 flags for 4 positions: Func = 0, <>f__AnonymousType0<string,string> = 0, List = 1, string = 2. The anonymous type's two string arguments get no flag at all, so the real type is Func<<>f__AnonymousType0<string, string>, List<string?>>.

Actual

Decompiling Repro.<>c (select it in the tree, or use the driver below):

public static Func<<>f__AnonymousType0<string, string?>, List<string>> <>9__0_1;

internal List<string?> <M>b__0_1(<>f__AnonymousType0<string, string> a)
{
	return new List<string>();
}

The ? moved off List's element onto the anonymous type's second property. The same two types are printed correctly on the lambda method right below it, whose parameter and return type each carry their own attribute.

Expected
public static Func<<>f__AnonymousType0<string, string>, List<string?>> <>9__0_1;
Driver (no GUI needed)
#:package [email protected]

using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.Metadata;

var path = args[0];
var resolver = new UniversalAssemblyResolver(path, throwOnError: false, targetFramework: null);
var decompiler = new CSharpDecompiler(path, resolver, new DecompilerSettings());
var c = decompiler.TypeSystem.MainModule.TypeDefinitions.Single(t => t.Name == "<>c");
Console.WriteLine(decompiler.DecompileAsString(c.MetadataToken));

dotnet run driver.cs -- AnonNullableRepro.dll. Reproduces on the released 9.1.0.7988 and on master (3f59de268).

Cause

ApplyAttributeTypeVisitor.VisitParameterizedType visits the type arguments of every parameterized type, and each reference-typed argument consumes one nullability flag. Roslyn treats an anonymous type as a single opaque position in the flag stream: in its symbol model the anonymous type is not generic, the type arguments are an emit-time artifact of the template, so no flags are written for them (their nullability is not representable in metadata). Every position after the anonymous type is therefore read too late; once the array is exhausted the remainder falls back to the enclosing NullableContext.

Where it showed up

Found by fuzzing nuget packages through the decompiler. Real-world hits, all on cached-lambda fields:

  • linq2db 6.4.0, ConvertBuilder+<>c__DisplayClass17_0: Func<<>f__AnonymousType5<MapValue, MapValueAttribute>, IEnumerable<ValueTuple<string, int>>> with Nullable([0,0,1,0,0])
  • brightsword.squid 2.0.0, BasicDataTransferObjectTypeCreator<T>+<>c::<>9__127_3: Func<<>f__AnonymousType6<KeyValuePair<Type, IBehaviour>, Type>, IEnumerable<Func<TypeBuilder, TypeBuilder>>> with Nullable([0,0,1,0,0,0])

In both, the byte count matches only if the anonymous type's arguments are skipped, and the shifted stream lands on a generic value type, which additionally trips Debug.Assert in ApplyAttributeTypeVisitor.ExpectDummyNullabilityForGenericValueType (ApplyAttributeTypeVisitor.cs:240).

Worth checking whether DynamicAttribute and TupleElementNamesAttribute use the same skip before changing the shared walk.


Written by an AI agent (Claude) on Siegfried's behalf.

Lingua principale
C#
Stelle
27.1k
Fork
3.8k
Merge medio
1g 23h
PR unite (30g)
44

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di icsharpcode/ILSpy

Tutte le issue di icsharpcode/ILSpy

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.