Expose more of the semantic model to the XPath queries of MA0240

Merged
ME
2mo ago
+328-25

The semantic attributes of MA0240 only exposed the name of a type and of a symbol, so a query could select a construct by what it is called, but not by what the symbol actually is — its accessibility, whether it is static, or whether its type is a value type.

What changed

Three new suffixes on each of the four type prefixes (Type, ConvertedType, ReturnType, ContainingType), so they follow the existing shape: semantic:TypeIsValueType, semantic:ConvertedTypeSpecialType, semantic:ReturnTypeNullableAnnotation, …

SuffixValue
…IsValueTypetrue / false
…NullableAnnotationAnnotated / NotAnnotated
…SpecialTypeThe name of the SpecialType member, such as System_Int32

Five new attributes about the symbol: semantic:ContainingSymbol, semantic:ContainingSymbolDocumentationId, semantic:ContainingSymbolKind, semantic:DeclaredAccessibility and semantic:IsStatic.

AddType now takes a TypeAttributeNames record instead of three name arguments, which keeps the four groups uniform and makes the dictionary of the valid names (used by MA0241 to report a typo) derive from them.

Behavior worth knowing when reviewing

All three are covered by tests:

  • NullableAnnotation is the annotation of the flow state of an expression: it is absent where the nullable context is disabled — including for int? — and absent on the nodes that are a type, such as the string? of a declaration. //IdentifierName[@semantic:TypeNullableAnnotation='Annotated'] works, //Parameter/*[…] does not.
  • SpecialType is absent when the type is not special, so not(@semantic:TypeSpecialType) is meaningful, and DeclaredAccessibility is absent for the symbols where it does not apply (Accessibility.NotApplicable), such as a local or a parameter.
  • The boolean attributes are present with the value false, unlike the other attributes, which are simply absent when they have no value. So [@semantic:TypeIsValueType='false'] selects the reference types whereas [not(@semantic:TypeIsValueType)] selects the nodes that have no type at all. This is documented.

The values are the names Roslyn produces, as the existing attributes are — no name invented by the rule, which is why SpecialType uses System_Int32 and not System.Int32.

Documentation

docs/Rules/MA0240.md now describes the type attributes as a prefix table plus a suffix table instead of an enumeration, and gains an examples table: boxing detection, public static methods, the operands of a string comparison with ==, references to a value that can be null, and the names contained in a given method.

Verification

  • The analyzer builds with no warnings on roslyn4.8 and roslyn5.9.
  • The 13 new tests and the existing ones pass on all five Roslyn versions (74 each).
  • The full roslyn5.9 suite passes (4871 tests).
  • dotnet run --project src/DocumentationGenerator exits 0 with no markdown change.