Skip to content

Commit

Permalink
Fix edge cases of getting attribute data from syntax (#75728)
Browse files Browse the repository at this point in the history
Fix two customer-discovered edge cases that were causing analyzer crashes.

Fixes #75681
Fixes #75706

Co-authored-by: Jeremy Koritzinsky <jekoritz@microsoft.com>
  • Loading branch information
github-actions[bot] and jkoritzinsky committed Sep 16, 2022
1 parent 6cf6e48 commit e0a65e0
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,17 @@ public static Location FindTypeExpressionOrNullLocation(this AttributeArgumentSy
switch (attributeTarget.Identifier.Kind())
{
case SyntaxKind.ReturnKeyword:
return ((IMethodSymbol)targetSymbol).GetReturnTypeAttributes().First(attributeSyntaxLocationMatches);
if (targetSymbol is IMethodSymbol method)
{
// Sometimes an attribute is put on a symbol that is nested within the containing symbol.
// For example, the ContainingSymbol for an AttributeSyntax on a local function have a ContainingSymbol of the method.
// Since this method is internal and the callers don't care about attributes on local functions,
// we just allow this method to return null in those cases.
return method.GetReturnTypeAttributes().FirstOrDefault(attributeSyntaxLocationMatches);
}
// An attribute on the return value of a delegate type's Invoke method has a ContainingSymbol of the delegate type.
// We don't care about the attributes in this case for the callers, so we'll just return null.
return null;
case SyntaxKind.AssemblyKeyword:
return targetSymbol.ContainingAssembly.GetAttributes().First(attributeSyntaxLocationMatches);
case SyntaxKind.ModuleKeyword:
Expand All @@ -43,7 +53,8 @@ public static Location FindTypeExpressionOrNullLocation(this AttributeArgumentSy
}
}
// Sometimes an attribute is put on a symbol that is nested within the containing symbol.
// For example, the ContainingSymbol for an AttributeSyntax on a parameter have a ContainingSymbol of the method.
// For example, the ContainingSymbol for an AttributeSyntax on a parameter have a ContainingSymbol of the method
// and an AttributeSyntax on a local function have a ContainingSymbol of the containing method.
// Since this method is internal and the callers don't care about attributes on parameters, we just allow
// this method to return null in those cases.
return targetSymbol.GetAttributes().FirstOrDefault(attributeSyntaxLocationMatches);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,8 +272,18 @@ public class X
{
void Foo([MarshalAs(UnmanagedType.I4)] int i)
{
[return:MarshalAs(UnmanagedType.I4)]
[SkipLocalsInit]
static int Local()
{
return 0;
}
}
}

[return:MarshalAs(UnmanagedType.I4)]
delegate int Y();

""";

await VerifyCS.VerifyAnalyzerAsync(source);
Expand Down

0 comments on commit e0a65e0

Please sign in to comment.