|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | + |
| 5 | +using System.Collections.Immutable; |
| 6 | +using System.Linq; |
| 7 | +using Microsoft.CodeAnalysis; |
| 8 | +using Microsoft.CodeAnalysis.CSharp; |
| 9 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 10 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 11 | + |
| 12 | +namespace Microsoft.ML.Analyzer |
| 13 | +{ |
| 14 | + [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 15 | + public sealed class TypeIsSchemaShapeAnalyzer : DiagnosticAnalyzer |
| 16 | + { |
| 17 | + internal static class ShapeDiagnostic |
| 18 | + { |
| 19 | + private const string Category = "Type Check"; |
| 20 | + public const string Id = "MSML_TypeShouldBeSchemaShape"; |
| 21 | + private const string Title = "The type is not a schema shape"; |
| 22 | + private const string Format = "Type{0} is neither a PipelineColumn nor a ValueTuple."; |
| 23 | + internal const string Description = |
| 24 | + "Within statically typed pipeline elements of ML.NET, the shape of the schema is determined by a type. " + |
| 25 | + "A valid type is either an instance of one of the PipelineColumn subclasses (e.g., Scalar<bool> " + |
| 26 | + "or something like that), or a ValueTuple containing only valid types. (So, ValueTuples containing " + |
| 27 | + "other value tuples are fine, so long as they terminate in a PipelineColumn subclass.)"; |
| 28 | + |
| 29 | + internal static DiagnosticDescriptor Rule = |
| 30 | + new DiagnosticDescriptor(Id, Title, Format, Category, |
| 31 | + DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description); |
| 32 | + } |
| 33 | + |
| 34 | + internal static class ShapeParameterDiagnostic |
| 35 | + { |
| 36 | + private const string Category = "Type Check"; |
| 37 | + public const string Id = "MSML_TypeParameterShouldBeSchemaShape"; |
| 38 | + private const string Title = "The type is not a schema shape"; |
| 39 | + private const string Format = "Type parameter {0} is not marked with [IsShape] or appropriate type constraints."; |
| 40 | + internal const string Description = ShapeDiagnostic.Description + " " + |
| 41 | + "If using type parameters when interacting with the statically typed pipelines, the type parameter ought to be " + |
| 42 | + "constrained in such a way that it, either by applying the [IsShape] attribute or by having type constraints to " + |
| 43 | + "indicate that it is valid, e.g., constraining the type to descend from PipelineColumn."; |
| 44 | + |
| 45 | + internal static DiagnosticDescriptor Rule = |
| 46 | + new DiagnosticDescriptor(Id, Title, Format, Category, |
| 47 | + DiagnosticSeverity.Error, isEnabledByDefault: true, description: Description); |
| 48 | + } |
| 49 | + |
| 50 | + private const string AttributeName = "Microsoft.ML.Data.StaticPipe.IsShapeAttribute"; |
| 51 | + private const string LeafTypeName = "Microsoft.ML.Data.StaticPipe.Runtime.PipelineColumn"; |
| 52 | + |
| 53 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => |
| 54 | + ImmutableArray.Create(ShapeDiagnostic.Rule, ShapeParameterDiagnostic.Rule); |
| 55 | + |
| 56 | + public override void Initialize(AnalysisContext context) |
| 57 | + { |
| 58 | + context.RegisterSemanticModelAction(Analyze); |
| 59 | + } |
| 60 | + |
| 61 | + private void Analyze(SemanticModelAnalysisContext context) |
| 62 | + { |
| 63 | + // We start with the model, then do the the method invocations. |
| 64 | + // We could have phrased it as RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression), |
| 65 | + // but this seemed more inefficient since getting the model and fetching the type symbols every |
| 66 | + // single time seems to incur significant cost. The following invocation is somewhat more awkward |
| 67 | + // since we must iterate over the invocation syntaxes ourselves, but this seems to be worthwhile. |
| 68 | + var model = context.SemanticModel; |
| 69 | + var comp = model.Compilation; |
| 70 | + |
| 71 | + // Get the symbols of the key types we are analyzing. If we can't find any of them there is |
| 72 | + // no point in going further. |
| 73 | + var attrType = comp.GetTypeByMetadataName(AttributeName); |
| 74 | + if (attrType == null) |
| 75 | + return; |
| 76 | + var leafType = comp.GetTypeByMetadataName(LeafTypeName); |
| 77 | + if (leafType == null) |
| 78 | + return; |
| 79 | + |
| 80 | + // This internal helper method recursively determines whether an attributed type parameter |
| 81 | + // has a valid type. It is called externally from the loop over invocations. |
| 82 | + bool CheckType(ITypeSymbol type, out string path, out ITypeSymbol problematicType) |
| 83 | + { |
| 84 | + if (type.TypeKind == TypeKind.TypeParameter) |
| 85 | + { |
| 86 | + var typeParam = (ITypeParameterSymbol)type; |
| 87 | + path = null; |
| 88 | + problematicType = null; |
| 89 | + // Does the type parameter have the attribute that triggers a check? |
| 90 | + if (type.GetAttributes().Any(attr => attr.AttributeClass == attrType)) |
| 91 | + return true; |
| 92 | + // Are any of the declared constraint types OK? |
| 93 | + if (typeParam.ConstraintTypes.Any(ct => CheckType(ct, out string ctPath, out var ctProb))) |
| 94 | + return true; |
| 95 | + // Well, probably not good then. Let's call it a day. |
| 96 | + problematicType = typeParam; |
| 97 | + return false; |
| 98 | + } |
| 99 | + else if (type.IsTupleType) |
| 100 | + { |
| 101 | + INamedTypeSymbol nameType = (INamedTypeSymbol)type; |
| 102 | + var tupleElems = nameType.TupleElements; |
| 103 | + |
| 104 | + for (int i = 0; i < tupleElems.Length; ++i) |
| 105 | + { |
| 106 | + var e = tupleElems[i]; |
| 107 | + if (!CheckType(e.Type, out string innerPath, out problematicType)) |
| 108 | + { |
| 109 | + path = e.Name ?? $"Item{i + 1}"; |
| 110 | + if (innerPath != null) |
| 111 | + path += "." + innerPath; |
| 112 | + return false; |
| 113 | + } |
| 114 | + } |
| 115 | + path = null; |
| 116 | + problematicType = null; |
| 117 | + return true; |
| 118 | + } |
| 119 | + else |
| 120 | + { |
| 121 | + for (var rt = type; rt != null; rt = rt.BaseType) |
| 122 | + { |
| 123 | + if (rt == leafType) |
| 124 | + { |
| 125 | + path = null; |
| 126 | + problematicType = null; |
| 127 | + return true; |
| 128 | + } |
| 129 | + } |
| 130 | + path = null; |
| 131 | + problematicType = type; |
| 132 | + return false; |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + foreach (var invocation in model.SyntaxTree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>()) |
| 137 | + { |
| 138 | + var symbolInfo = model.GetSymbolInfo(invocation); |
| 139 | + if (!(symbolInfo.Symbol is IMethodSymbol methodSymbol)) |
| 140 | + { |
| 141 | + // Should we perhaps skip when there is a method resolution failure? This is often but not always a sign of another problem. |
| 142 | + if (symbolInfo.CandidateReason != CandidateReason.OverloadResolutionFailure || symbolInfo.CandidateSymbols.Length == 0) |
| 143 | + continue; |
| 144 | + methodSymbol = symbolInfo.CandidateSymbols[0] as IMethodSymbol; |
| 145 | + if (methodSymbol == null) |
| 146 | + continue; |
| 147 | + } |
| 148 | + // Analysis only applies to generic methods. |
| 149 | + if (!methodSymbol.IsGenericMethod) |
| 150 | + continue; |
| 151 | + // Scan the type parameters for one that has our target attribute. |
| 152 | + for (int i = 0; i < methodSymbol.TypeParameters.Length; ++i) |
| 153 | + { |
| 154 | + var par = methodSymbol.TypeParameters[i]; |
| 155 | + var attr = par.GetAttributes(); |
| 156 | + if (attr.Length == 0) |
| 157 | + continue; |
| 158 | + if (!attr.Any(a => a.AttributeClass == attrType)) |
| 159 | + continue; |
| 160 | + // We've found it. Check the type argument to ensure it is of the appropriate type. |
| 161 | + var p = methodSymbol.TypeArguments[i]; |
| 162 | + if (CheckType(p, out string path, out ITypeSymbol problematicType)) |
| 163 | + continue; |
| 164 | + |
| 165 | + if (problematicType.Kind == SymbolKind.TypeParameter) |
| 166 | + { |
| 167 | + var diagnostic = Diagnostic.Create(ShapeParameterDiagnostic.Rule, invocation.GetLocation(), problematicType.Name); |
| 168 | + context.ReportDiagnostic(diagnostic); |
| 169 | + } |
| 170 | + else |
| 171 | + { |
| 172 | + path = path == null ? "" : " of item " + path; |
| 173 | + var diagnostic = Diagnostic.Create(ShapeDiagnostic.Rule, invocation.GetLocation(), path); |
| 174 | + context.ReportDiagnostic(diagnostic); |
| 175 | + } |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | + } |
| 180 | +} |
0 commit comments