public void Analyze(SemanticModelAnalysisContext context, OptionSet options) { foreach (var analyer in _analyzers) { analyer.Analyze(context, options); } }
private static void CreateDiagnosticsFromMatchingNodes(SemanticModelAnalysisContext context, IEnumerable<AttributeSyntax> matchingNodes) { foreach (var matchingNode in matchingNodes) { ReportDiagnostic(context, matchingNode); } }
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var tree = context.SemanticModel.SyntaxTree; var cancellationToken = context.CancellationToken; var workspace = ((WorkspaceAnalyzerOptions)context.Options).Workspace; var service = workspace.Services.GetLanguageServices(context.SemanticModel.Compilation.Language) .GetService<IUnnecessaryImportsService>(); var unnecessaryImports = service.GetUnnecessaryImports(context.SemanticModel, cancellationToken); if (unnecessaryImports.Any()) { // The IUnnecessaryImportsService will return individual import pieces that // need to be removed. For example, it will return individual import-clauses // from VB. However, we want to mark the entire import statement if we are // going to remove all the clause. Defer to our subclass to stitch this up // for us appropriately. unnecessaryImports = MergeImports(unnecessaryImports); Func<SyntaxNode, SyntaxToken> getLastTokenFunc = GetLastTokenDelegateForContiguousSpans(); var contiguousSpans = unnecessaryImports.GetContiguousSpans(getLastTokenFunc); var diagnostics = CreateClassificationDiagnostics(contiguousSpans, tree, cancellationToken).Concat( CreateFixableDiagnostics(unnecessaryImports, tree, cancellationToken)); foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } }
public Analyzer(DiagnosticDescriptor rule, SemanticModelAnalysisContext context, IDictionary <string, ControlFlowGraph> methods) { _rule = rule; _context = context; _methods = methods; _semanticModel = context.SemanticModel; }
private static async void Analyze(SemanticModelAnalysisContext context) { var root = await context.SemanticModel.SyntaxTree.GetRootAsync(); var invocations = root.DescendantNodes().OfType<InvocationExpressionSyntax>(); var bindBuffers = invocations.Where(i => i.GetMethodCallingName() == nameof(GL) + "." + nameof(GL.BindBuffer)); var syntaxValidBinds = bindBuffers.Where(b => b.ArgumentList.Arguments.Count == 2); var constantInvalidBinds = syntaxValidBinds.Select(b => b.GetArgumentExpressionAt(1)) .Where(e => { var constant = context.SemanticModel.GetConstantValue(e); return constant.HasValue && !constant.Value.Equals(0); }); // null(not constant) or 0 are valid so be false foreach (var bindLiteral in constantInvalidBinds) { context.ReportDiagnostic(Diagnostic.Create( descriptor: NoConstantRule, location: bindLiteral.GetLocation())); } var variableBindGroups = syntaxValidBinds.GroupBy(b => Identifier.GetVariableString(b.GetArgumentExpressionAt(1), context.SemanticModel)) .Where(g => !string.IsNullOrEmpty(g.Key)); // <- constant on second argument foreach (var group in variableBindGroups) { var targets = group.GroupBy(b => context.SemanticModel.GetSymbolInfo(b.GetArgumentExpressionAt(0))).Where(t => t.Key.Symbol != null); if (targets.Skip(1).Any()) { foreach (var invocation in group) { context.ReportDiagnostic(Diagnostic.Create( descriptor: TargetRule, location: invocation.GetLocation(), messageArgs: new[] { Identifier.GetSimpleName(group.Key), string.Join(", ", targets.Select(t => nameof(BufferTarget) + "." + t.Key.Symbol.Name)) })); } } } }
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var cancellationToken = context.CancellationToken; var semanticModel = context.SemanticModel; // Don't even bother doing the analysis if the user doesn't even want auto-props. var option = context.GetOption(CodeStyleOptions2.PreferAutoProperties, semanticModel.Language); if (!option.Value) { return; } var analysisResults = new List <AnalysisResult>(); var ineligibleFields = new HashSet <IFieldSymbol>(); var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); AnalyzeCompilationUnit(context, root, analysisResults); RegisterIneligibleFieldsAction( analysisResults, ineligibleFields, semanticModel.Compilation, cancellationToken); Process(analysisResults, ineligibleFields, context); }
private void VerifyRule(SemanticModelAnalysisContext context, IEnumerable<dynamic> fieldsInfo) { foreach (var violatedField in GetRuleViolations(fieldsInfo.ToList())) { context.ReportDiagnostic(Diagnostic.Create(Rule, violatedField.Declaration.Variables[0].Identifier.GetLocation())); } }
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { SyntaxTree st = context.SemanticModel.SyntaxTree; if (IgnoreSourceDocumentFile(st.FilePath)) return; CompilationUnitSyntax rootSyntax = st.GetRoot() as CompilationUnitSyntax; if (rootSyntax == null) return; IEnumerable<MethodDeclarationSyntax> methodDeclarations = rootSyntax.DescendantNodes().OfType<MethodDeclarationSyntax>(); if (methodDeclarations.Count() == 0) return; SymbolInfo symbolInfo; foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { symbolInfo = context.SemanticModel.GetSymbolInfo(methodDeclaration.ReturnType); if (symbolInfo.Symbol?.Name == "Task" && !methodDeclaration.Identifier.Text.EndsWith("Async")) { context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.NameOfAwaitableMethodEndWithAsync , methodDeclaration.Identifier.GetLocation())); } } }
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { if (context.IsFromGeneratedCode()) { return; } var tree = context.SemanticModel.SyntaxTree; var root = tree.GetRoot(); var unncessaryImports = GetUnnecessaryImports(context.SemanticModel, root); if (unncessaryImports != null && unncessaryImports.Any()) { Func <SyntaxNode, SyntaxToken> getLastTokenFunc = GetLastTokenDelegateForContiguousSpans(); var contiguousSpans = unncessaryImports.GetContiguousSpans(getLastTokenFunc); var diagnostics = CreateClassificationDiagnostics(contiguousSpans, tree).Concat( CreateFixableDiagnostics(unncessaryImports, tree)); var spans = new List <TextSpan> (); foreach (var diagnostic in diagnostics) { if (spans.Any(s => s.OverlapsWith(diagnostic.Location.SourceSpan))) { continue; } spans.Add(diagnostic.Location.SourceSpan); context.ReportDiagnostic(diagnostic); } } }
public static void ReportDiagnosticsIfValid(SemanticModelAnalysisContext context, DiagnosticDescriptor descriptor, CSharpSyntaxNode node, params object[] messageArgs) { if (ShouldReportAnalyzerReport(node)) { context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), messageArgs)); } }
/// <summary> /// Performs the analysis. /// </summary> /// <param name="context">The context in which the analysis should be performed.</param> private static void Analyze(SemanticModelAnalysisContext context) { var enumDeclarations = context .SemanticModel .SyntaxTree.Descendants<EnumDeclarationSyntax>(); foreach (var enumDeclaration in enumDeclarations) { if (enumDeclaration.BaseList != null) { _explicitEnumType.Emit(context, enumDeclaration.BaseList.Types.First(), context.SemanticModel.GetDeclaredSymbol(enumDeclaration).ToDisplayString()); } var enumMembers = enumDeclaration .Descendants<EnumMemberDeclarationSyntax>() .Where(enumMember => enumMember.EqualsValue != null); foreach (var enumMember in enumMembers) { _explicitEnumMemberValue.Emit(context, enumMember.EqualsValue.Value, context.SemanticModel.GetDeclaredSymbol(enumMember).ToDisplayString()); } } }
private static void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var model = context.SemanticModel; var debuggerStepThroughAttributeSymbol = GetDebuggerStepThroughAttributeSymbol(model); var matchingAttributes = FindMatchingNodes(model, debuggerStepThroughAttributeSymbol); CreateDiagnosticsFromMatchingNodes(context, matchingAttributes); }
public static void Analyze(SemanticModelAnalysisContext context) { var semanticModel = context.SemanticModel; var variableDeclarations = semanticModel.SyntaxTree .GetRoot() .DescendantNodes() .OfType <VariableDeclarationSyntax>() .Where(node => node.Ancestors().OfType <LocalDeclarationStatementSyntax>().Any() ); foreach (var declaration in variableDeclarations) { var symbol = semanticModel.GetSymbolInfo(declaration.Type).Symbol; var symbolType = semanticModel.GetTypeInfo(declaration.Type).Type; if (symbolType.SpecialType != SpecialType.System_Boolean) { continue; } foreach (var variable in declaration.Variables) { if (!AvailablePrefixes.Any(ap => variable.Identifier.Text.StartsWith(ap))) { context.ReportDiagnostic(Diagnostic.Create(Rule, variable.Identifier.GetLocation(), symbol.Name)); } } } }
public TestVisitor(SemanticModelAnalysisContext context) { _ReportDiagnostic = context.ReportDiagnostic; _Compilation = context.SemanticModel.Compilation; _TestingFrameworks = new TestingFrameworks(_Compilation); if (!IsTestProject) { // This is not a Testing Project return; } var smartTest = _Compilation.GetTypeByMetadataName(_SmartTestClassName); if (smartTest == null) { // This is not a SmartTest Project! return; } IsSmartTestProject = IsTestProject; _CaseType = _Compilation.GetTypeByMetadataName("SmartTests.Case"); Debug.Assert(_CaseType != null); _ErrorType = _Compilation.GetTypeByMetadataName("SmartTests.ErrorAttribute"); Debug.Assert(_ErrorType != null); _RunTestMethods = smartTest.GetMethods("RunTest"); _CaseMethods = smartTest.GetMethods("Case"); _ErrorCaseMethods = smartTest.GetMethods("ErrorCase"); _AssignMethods = smartTest.GetMethods("Assign"); }
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var fadeCode = context.Options.GetIdeOptions().FadeOutUnreachableCode; var semanticModel = context.SemanticModel; var cancellationToken = context.CancellationToken; // There is no good existing API to check if a statement is unreachable in an efficient // manner. While there is SemanticModel.AnalyzeControlFlow, it can only operate on a // statement at a time, and it will reanalyze and allocate on each call. // // To avoid this, we simply ask the semantic model for all the diagnostics for this // block and we look for any reported "unreachable code detected" diagnostics. // // This is actually quite fast to do because the compiler does not actually need to // recompile things to determine the diagnostics. It will have already stashed the // binding diagnostics directly on the SourceMethodSymbol containing this block, and // so it can retrieve the diagnostics at practically no cost. var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken); foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); if (diagnostic.Id == CS0162) { ProcessUnreachableDiagnostic(context, root, diagnostic.Location.SourceSpan, fadeCode); } } }
private bool HasJNIConstructor(ClassDeclarationSyntax classDeclaration, SemanticModelAnalysisContext context, INamedTypeSymbol intPtrType, INamedTypeSymbol jniHandleOwnershipType) { foreach (MemberDeclarationSyntax member in classDeclaration.Members) { if (member.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructorDeclaration = member as ConstructorDeclarationSyntax; if (constructorDeclaration.ParameterList.Parameters.Count == 2) { ParameterSyntax parameterIntPtr = constructorDeclaration.ParameterList.Parameters[0]; ParameterSyntax parameterJniHandleOwnership = constructorDeclaration.ParameterList.Parameters[1]; // Has correct parameters if (IsType(parameterIntPtr, intPtrType, context) && IsType(parameterJniHandleOwnership, jniHandleOwnershipType, context)) { // Base is called correctly... if (constructorDeclaration.Initializer is { } initializer&& initializer.ThisOrBaseKeyword.IsKind(SyntaxKind.BaseKeyword) && initializer.ArgumentList is { } argumentList&& argumentList.Arguments is { } arguments&& arguments.Count == 2 && IsSameParameter(arguments[0], parameterIntPtr) && IsSameParameter(arguments[1], parameterJniHandleOwnership) ) { return(true); } } } } } return(false);
private static void CreateDiagnosticForMappingCall(SemanticModelAnalysisContext context, KeyValuePair <MappingPair, ICollection <Location> > mappingCall) { foreach (var location in mappingCall.Value) { var diagnostic = Diagnostic.Create(Rule, location); context.ReportDiagnostic(diagnostic); } }
private static void ReportType(SemanticModelAnalysisContext context, [NotNull] SyntaxNode typeSyntax) { string fileName = Path.GetFileName(context.SemanticModel.SyntaxTree.FilePath); ISymbol symbol = context.SemanticModel.GetDeclaredSymbol(typeSyntax, context.CancellationToken); string typeName = symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat); context.ReportDiagnostic(Diagnostic.Create(Rule, symbol.Locations[0], fileName, typeName)); }
public static void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var declDiagnostics = context.SemanticModel.GetDeclarationDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(declDiagnostics, context.ReportDiagnostic, IsSourceLocation, s_declaration); var bodyDiagnostics = context.SemanticModel.GetMethodBodyDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(bodyDiagnostics, context.ReportDiagnostic, IsSourceLocation); }
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { ConsoleWriteAnalyzer.Run(context); StringConcatenationWithImplicitConversionAnalyzer.Run(context); ExplicitToStringWithoutOverrideAnalyzer.Run(context); StringFormatArgumentImplicitToStringAnalyzer.Run(context); InterpolatedStringImplicitToStringAnalyzer.Run(context); }
private static AttributeSyntax[] GetAllAttribute(SemanticModelAnalysisContext context) => context .SemanticModel .SyntaxTree .GetRoot() .DescendantNodes() .OfType <AttributeSyntax>() .ToArray();
private void SemanticAction(SemanticModelAnalysisContext context) { SemanticModel semanticModel = context.SemanticModel; var model = semanticModel.SyntaxTree.GetRoot(); var walker = new Walker(semanticModel, context); walker.Visit(model); }
private void AnalyzeModel(SemanticModelAnalysisContext context) { var startingLocations = InMethods.SelectMany(GetMethodLocation); foreach (var node in FindSyntaxNodes(_methodInvocationsWithSymbols, _syntaxNodesWithSymbols, startingLocations)) { AnalyzeNodeInMethod(context, node); } }
private void Process(AnalysisResult result, SemanticModelAnalysisContext context) { // Check if there are additional reasons we think this field might be ineligible for // replacing with an auto prop. var cancellationToken = context.CancellationToken; var semanticModel = context.SemanticModel; var compilation = semanticModel.Compilation; if (!IsEligibleHeuristic(result.Field, result.PropertyDeclaration, compilation, cancellationToken)) { return; } var propertyDeclaration = result.PropertyDeclaration; var variableDeclarator = result.VariableDeclarator; var nodeToFade = GetNodeToFade(result.FieldDeclaration, variableDeclarator); var optionSet = context.Options.GetDocumentOptionSetAsync( result.FieldDeclaration.SyntaxTree, cancellationToken).GetAwaiter().GetResult(); if (optionSet == null) { return; } // Now add diagnostics to both the field and the property saying we can convert it to // an auto property. For each diagnostic store both location so we can easily retrieve // them when performing the code fix. var additionalLocations = ImmutableArray.Create( propertyDeclaration.GetLocation(), variableDeclarator.GetLocation()); var option = optionSet.GetOption(CodeStyleOptions.PreferAutoProperties, propertyDeclaration.Language); if (option.Notification.Severity == ReportDiagnostic.Suppress) { // Avoid reporting diagnostics when the feature is disabled. This primarily avoids reporting the hidden // helper diagnostic which is not otherwise influenced by the severity settings. return; } // Place the appropriate marker on the field depending on the user option. var diagnostic1 = DiagnosticHelper.Create( UnnecessaryWithSuggestionDescriptor, nodeToFade.GetLocation(), option.Notification.Severity, additionalLocations: additionalLocations, properties: null); // Also, place a hidden marker on the property. If they bring up a lightbulb // there, they'll be able to see that they can convert it to an auto-prop. var diagnostic2 = Diagnostic.Create( Descriptor, propertyDeclaration.GetLocation(), additionalLocations: additionalLocations); context.ReportDiagnostic(diagnostic1); context.ReportDiagnostic(diagnostic2); }
private static void AnalyzeModel( SemanticModelAnalysisContext context) { var model = context.SemanticModel; var root = model.SyntaxTree.GetCompilationUnitRoot( context.CancellationToken); var all = root.DescendantNodes() .OfType <ClassDeclarationSyntax>(); if (!all.Any()) { return; } var cancellationToken = context.CancellationToken; foreach (var node in all) { var classSymbol = model.GetDeclaredSymbol(node, cancellationToken); var typeParameterList = node.TypeParameterList; if (classSymbol is null || !classSymbol.IsStatic || typeParameterList is null || !typeParameterList.Parameters.Any()) { continue; } bool IsClassTypeParameter(ISymbol s) => s.Kind == SymbolKind.TypeParameter && Equals(s.ContainingSymbol, classSymbol); bool IsTargetMethod(MethodDeclarationSyntax m) => m.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.IdentifierName)) .Select(n => model.GetSymbolInfo(n, cancellationToken)) .Select(i => i.Symbol) .FilterNonNullReference() .Any(IsClassTypeParameter); var firstMethod = node.Members .OfType <MethodDeclarationSyntax>() .FirstOrDefault(m => IsTargetMethod(m)); if (firstMethod is null) { continue; } var location = node.ChildTokens() .First(t => t.IsKind(SyntaxKind.IdentifierToken)) .GetLocation(); var diagnostic = Diagnostic.Create( Rule, location, classSymbol.Name); context.ReportDiagnostic(diagnostic); } }
public DoNotUseUnversionedTypesInVersionedApisAnalyzerImplementation( SemanticModelAnalysisContext context, KnownTypes knownTypes, TypeVersionChecker typeVersionChecker) { _context = context; _knownTypes = knownTypes; _typeVersionChecker = typeVersionChecker; }
private void AnalyzeMembers( SemanticModelAnalysisContext context, SyntaxList <MemberDeclarationSyntax> members, List <AnalysisResult> analysisResults) { foreach (var memberDeclaration in members) { AnalyzeMemberDeclaration(context, memberDeclaration, analysisResults); } }
public Visitor( SemanticModelAnalysisContext context, KnownTypes knownTypes, TypeVersionChecker typeVersionChecker) { _context = context; SemanticModel = context.SemanticModel; Compilation = SemanticModel.Compilation; KnownTypes = knownTypes; _typeVersionChecker = typeVersionChecker; }
private static void AnalyzeSemantic(SemanticModelAnalysisContext context) { var model = context.SemanticModel; var result = AnalyzeForMappings(model); foreach (var item in result) { context.ReportDiagnostic(CreateDiagnostic(item)); } ; }
private static void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { SyntaxNode syntaxRoot = context.SemanticModel.SyntaxTree.GetRoot(context.CancellationToken); var walker = new TopLevelTypeSyntaxWalker(); walker.Visit(syntaxRoot); context.CancellationToken.ThrowIfCancellationRequested(); ReportWalkerResult(walker, context); }
private static void AnalyzeModel( SemanticModelAnalysisContext context) { var cancellationToken = context.CancellationToken; var model = context.SemanticModel; var root = model.SyntaxTree.GetCompilationUnitRoot( cancellationToken); CheckLocal(context, model); CheckParameter(context, model, root); }
private void SemanticModelAction(SemanticModelAnalysisContext context) { var types = GetAllTypes(context.SemanticModel.Compilation).ToArray(); var attributes = GetAllAttribute(context); var ambiguities = GetAmbiguities(types, attributes); foreach (var ambiguity in ambiguities) { context.ReportDiagnostic(ambiguity); } }
public void Analyze(SemanticModelAnalysisContext context) { var semanticModel = context.SemanticModel; var syntaxTree = semanticModel.SyntaxTree; var cancellationToken = context.CancellationToken; var options = context.Options; var optionSet = options.GetDocumentOptionSetAsync( semanticModel.SyntaxTree, cancellationToken).GetAwaiter().GetResult(); if (optionSet == null) { return; } var option = optionSet.GetOption(RegularExpressionsOptions.ReportInvalidRegexPatterns, syntaxTree.Options.Language); if (!option) { return; } var detector = RegexPatternDetector.TryGetOrCreate(semanticModel, _info); if (detector == null) { return; } // Use an actual stack object so that we don't blow the actual stack through recursion. var root = syntaxTree.GetRoot(cancellationToken); var stack = new Stack <SyntaxNode>(); stack.Push(root); while (stack.Count != 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); foreach (var child in current.ChildNodesAndTokens()) { if (child.IsNode) { stack.Push(child.AsNode()); } else { AnalyzeToken(context, detector, child.AsToken(), cancellationToken); } } } }
private static void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { // Find just those source files with declaration diagnostics. var diagnosticsCount = context.SemanticModel.GetDeclarationDiagnostics().Length; if (diagnosticsCount > 0) { // For all such files, produce a diagnostic. var diagnostic = Diagnostic.Create(Rule, Location.None, Path.GetFileName(context.SemanticModel.SyntaxTree.FilePath), diagnosticsCount); context.ReportDiagnostic(diagnostic); } }
private static void createDiagnostic(SemanticModelAnalysisContext context, Location location, string typeName, List <string> requiredMembers) { DiagnosticDescriptor rule = singlePropertyRule; if (requiredMembers.Count > 1) { rule = multiplePropertyRule; } var diagnostic = Diagnostic.Create(rule, location, typeName, string.Join(", ", requiredMembers)); context.ReportDiagnostic(diagnostic); }
private static void _AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var semanticModel = context.SemanticModel; var nodes = semanticModel.SyntaxTree.GetRoot().DescendantNodes() .OfType <InvocationExpressionSyntax>() .Where(i => i.IsParallelFor(context.SemanticModel)); foreach (InvocationExpressionSyntax invocation in nodes) { _AnalyzeParallelForLoop(invocation, context); } }
private static void AnalyzeClass(SemanticModelAnalysisContext context) { var syntaxTree = context.SemanticModel.SyntaxTree; var classSyntax = syntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().FirstOrDefault(); if (classSyntax == null) { return; } if (!classSyntax.Modifiers.Any(x => x != SyntaxFactory.Token(SyntaxKind.StaticKeyword))) { var diagnostic = Diagnostic.Create(Rule, Location.Create(syntaxTree, classSyntax.Span)); context.ReportDiagnostic(diagnostic); } }
private async void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var root = await context.SemanticModel.SyntaxTree.GetRootAsync(); foreach (var classDeclaration in root.DescendantNodesAndSelf().OfType<ClassDeclarationSyntax>()) { var collection = classDeclaration.DescendantNodes().OfType<FieldDeclarationSyntax>().Select(f => new { IsCollection = IsCollection(f, context.SemanticModel), Syntax = f } ); VerifyRule(context, collection); } }
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var tree = context.SemanticModel.SyntaxTree; var root = tree.GetRoot(); var unncessaryImports = GetUnnecessaryImports(context.SemanticModel, root); if (unncessaryImports != null && unncessaryImports.Any()) { Func<SyntaxNode, SyntaxToken> getLastTokenFunc = GetLastTokenDelegateForContiguousSpans(); var contiguousSpans = unncessaryImports.GetContiguousSpans(getLastTokenFunc); var diagnostics = CreateClassificationDiagnostics(contiguousSpans, tree).Concat( CreateFixableDiagnostics(unncessaryImports, tree)); foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } }
private static void AnalyzeSemantic(SemanticModelAnalysisContext semanticContext) { var testSemanticModel = semanticContext.SemanticModel; var methodDecls = TestSemanticHelper.GetTestMethods(testSemanticModel); var methods = TestSemanticHelper.GetMethodsToConfigureMocks(methodDecls); var properties = TestSemanticHelper.GetPropertiesToConfigureMocks(methodDecls, methods); var memberAccessExpressions = methods.Concat(properties) .ToArray(); if (!memberAccessExpressions.Any()) return; var testInitMethodDecl = TestSemanticHelper.GetTestInitializeMethod(testSemanticModel); if(testInitMethodDecl == null) return; var declaredFields = testInitMethodDecl.Parent.ChildNodes().OfType<FieldDeclarationSyntax>().ToArray(); var suts = testInitMethodDecl.GetSuts(testSemanticModel, declaredFields); var sutIdentifiers = suts.Select(x => x.Identifier.Identifier.Text).ToArray(); memberAccessExpressions = memberAccessExpressions.Where(x => x.DescendantNodesAndSelf() .Any(y => sutIdentifiers.Contains((y as IdentifierNameSyntax)?.Identifier.Text))) .ToArray(); var mockableExpressions = memberAccessExpressions.Where(expressionSyntax => !IsNotExpressionNeedsToMock(MocksAnalyzingEngine.GetInvokedMethodsOfMock(expressionSyntax, testSemanticModel, suts) .SelectMany(x => x.FieldsToSetup .SelectMany(y => y.Field)) .Distinct() .ToArray(), expressionSyntax)) .ToArray(); foreach (var mockableExpression in mockableExpressions) { semanticContext.ReportDiagnostic(Diagnostic.Create(Rule, mockableExpression.Parent.GetLocation())); } }
private static void AnalyzeSemantic(SemanticModelAnalysisContext semanticModel) { var methodDecl = TestSemanticHelper.GetTestInitializeMethod(semanticModel.SemanticModel); var expression = methodDecl?.DescendantNodes() .OfType<ObjectCreationExpressionSyntax>() .FirstOrDefault(x => x.ArgumentList.Arguments.Count == 0); if (expression == null) return; var symbolInfo = semanticModel.SemanticModel.GetSymbolInfo(expression); if (symbolInfo.CandidateReason != CandidateReason.OverloadResolutionFailure) return; var invokedSymbol = symbolInfo.CandidateSymbols.FirstOrDefault(x => x is IMethodSymbol /*&&((IMethodSymbol) x).Parameters.All(y => y.Type.IsAbstract)*/); if (invokedSymbol != null) semanticModel.ReportDiagnostic(Diagnostic.Create(Rule, expression.Parent.GetLocation())); }
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { if (context.IsFromGeneratedCode ()) return; var tree = context.SemanticModel.SyntaxTree; var root = tree.GetRoot(); var unncessaryImports = GetUnnecessaryImports(context.SemanticModel, root); if (unncessaryImports != null && unncessaryImports.Any()) { Func<SyntaxNode, SyntaxToken> getLastTokenFunc = GetLastTokenDelegateForContiguousSpans(); var contiguousSpans = unncessaryImports.GetContiguousSpans(getLastTokenFunc); var diagnostics = CreateClassificationDiagnostics(contiguousSpans, tree).Concat( CreateFixableDiagnostics(unncessaryImports, tree)); var spans = new List<TextSpan> (); foreach (var diagnostic in diagnostics) { if (spans.Any (s => s.OverlapsWith (diagnostic.Location.SourceSpan))) continue; spans.Add (diagnostic.Location.SourceSpan); context.ReportDiagnostic(diagnostic); } } }
private static async void Analyze(SemanticModelAnalysisContext context) { var root = await context.SemanticModel.SyntaxTree.GetRootAsync(); var invocations = root.DescendantNodes().OfType<InvocationExpressionSyntax>(); // check for GL.GenBuffer (single one) var genBufferOps = invocations.Where(i => i.GetMethodCallingName() == nameof(GL) + "." + nameof(GL.GenBuffer)); var notUsedGenBufferOps = genBufferOps.Where(g => !g.Parent.IsKind(SyntaxKind.SimpleAssignmentExpression) && !g.Parent.IsKind(SyntaxKind.EqualsValueClause)); foreach (var genOp in notUsedGenBufferOps) { context.ReportDiagnostic(Diagnostic.Create( descriptor: NotUsedRule, location: genOp.GetLocation())); } // check for GL.GenBuffers (multiple one) var genBuffersOps = invocations.Where(i => i.GetMethodCallingName() == nameof(GL) + "." + nameof(GL.GenBuffers)); var firstArgConstGenBuffersOps = GetFirstArgConstInt(genBuffersOps); foreach (var genOp in FindNonNatural(firstArgConstGenBuffersOps)) { context.ReportDiagnostic(Diagnostic.Create( descriptor: BuffersNumberRule, location: genOp.GetArgumentExpressionAt(0).GetLocation(), messageArgs: nameof(GL) + "." + nameof(GL.GenBuffers))); } foreach (var genOp in FindNotOneInvalid(firstArgConstGenBuffersOps)) { context.ReportDiagnostic(Diagnostic.Create( descriptor: GenDeleteOneBufferRule, location: genOp.GetArgumentExpressionAt(0).GetLocation())); } // check for GL.DeleteBuffer (single one) var deleteBufferOps = invocations.Where(i => i.GetMethodCallingName() == nameof(GL) + "." + nameof(GL.DeleteBuffer)); var invalidDeleteBufferOps = GetFirstArgConstInt(deleteBufferOps).Where(o => o.Item2.HasValue); foreach (var deleteLiteral in invalidDeleteBufferOps) { context.ReportDiagnostic(Diagnostic.Create( descriptor: NoConstantRule, location: deleteLiteral.Item1.GetArgumentExpressionAt(0).GetLocation(), messageArgs: nameof(GL) + "." + nameof(GL.DeleteBuffer))); } // check for GL.DeleteBuffers (multiple one) var deleteBuffersOps = invocations.Where(i => i.GetMethodCallingName() == nameof(GL) + "." + nameof(GL.DeleteBuffers)); var firstArgConstDeleteBuffersOps = GetFirstArgConstInt(deleteBuffersOps); foreach (var deleteOp in FindNonNatural(firstArgConstDeleteBuffersOps)) { context.ReportDiagnostic(Diagnostic.Create( descriptor: BuffersNumberRule, location: deleteOp.GetArgumentExpressionAt(0).GetLocation(), messageArgs: nameof(GL) + "." + nameof(GL.DeleteBuffers))); } foreach (var deleteOp in FindNotOneInvalid(firstArgConstDeleteBuffersOps)) { context.ReportDiagnostic(Diagnostic.Create( descriptor: GenDeleteOneBufferRule, location: deleteOp.GetArgumentExpressionAt(0).GetLocation())); } // GL.GenBuffers and GL.DeleteBuffers complex inspection var genOpGroupsById = GroupByVariableName(firstArgConstGenBuffersOps, context.SemanticModel); var deleteOpGroupsById = GroupByVariableName(firstArgConstDeleteBuffersOps, context.SemanticModel); // pick up all variable names var allKeys = Enumerable.Union(genOpGroupsById.Select(g => g.Key), deleteOpGroupsById.Select(d => d.Key)); foreach (var key in allKeys) { var genOps = genOpGroupsById.FirstOrDefault(g => g.Key == key); var deleteOps = deleteOpGroupsById.FirstOrDefault(d => d.Key == key); bool isGenOpValid = true; bool isDeleteOpValid = true; if (genOps == null) { foreach (var delete in deleteOps) { var variableName = Identifier.GetSimpleName(key); context.ReportDiagnostic(Diagnostic.Create( descriptor: LackGenBuffersRule, location: delete.Item1.GetLocation(), messageArgs: variableName)); } isGenOpValid = false; } if (deleteOps == null) { foreach (var gen in genOps) { var variableName = Identifier.GetSimpleName(key); context.ReportDiagnostic(Diagnostic.Create( descriptor: LackDeleteBuffersRule, location: gen.Item1.GetLocation(), messageArgs: variableName)); } isDeleteOpValid = false; } if (isGenOpValid && genOps.Skip(1).Any()) // 2 or more gens with same variable { foreach (var gen in genOps) { var variableName = Identifier.GetSimpleName(key); context.ReportDiagnostic(Diagnostic.Create( descriptor: DuplexBuffersRule, location: gen.Item1.GetLocation(), messageArgs: new[] { variableName, nameof(GL) + "." + nameof(GL.GenBuffers) })); } isGenOpValid = false; } if (isDeleteOpValid && deleteOps.Skip(1).Any()) // 2 or more deletes with same variable { foreach (var delete in deleteOps) { var variableName = Identifier.GetSimpleName(key); context.ReportDiagnostic(Diagnostic.Create( descriptor: DuplexBuffersRule, location: delete.Item1.GetLocation(), messageArgs: new[] { variableName, nameof(GL) + "." + nameof(GL.DeleteBuffers) })); } isDeleteOpValid = false; } if (!isGenOpValid || !isDeleteOpValid) { continue; } // gen and delete are 1 to 1, but constant might different var genOp = genOps.First(); var deleteOp = deleteOps.First(); if (genOp.Item2.HasValue && deleteOp.Item2.HasValue) { if (genOp.Item2.Value != deleteOp.Item2.Value) { var variableName = Identifier.GetSimpleName(key); context.ReportDiagnostic(Diagnostic.Create( descriptor: GenDeleteNumberOfBuffersRule, location: genOp.Item1.GetLocation(), messageArgs: variableName)); context.ReportDiagnostic(Diagnostic.Create( descriptor: GenDeleteNumberOfBuffersRule, location: deleteOp.Item1.GetLocation(), messageArgs: variableName)); } } // one is constant and another is variable so this usually wrong else if (genOp.Item2.HasValue || deleteOp.Item2.HasValue) { var variableName = Identifier.GetSimpleName(key); context.ReportDiagnostic(Diagnostic.Create( descriptor: GenDeleteNumberOfBuffersRule, location: genOp.Item1.GetLocation(), messageArgs: variableName)); context.ReportDiagnostic(Diagnostic.Create( descriptor: GenDeleteNumberOfBuffersRule, location: deleteOp.Item1.GetLocation(), messageArgs: variableName)); } } }
private static async void Analyze(SemanticModelAnalysisContext context) { var root = await context.SemanticModel.SyntaxTree.GetRootAsync(); var invocations = root.DescendantNodes().OfType<InvocationExpressionSyntax>(); var lights = invocations.Where(i => i.GetMethodCallingName() == nameof(GL) + "." + nameof(GL.Light)); foreach (var lightOp in lights) { if (lightOp.ArgumentList.Arguments.Count == 3) { var secondExpression = lightOp.GetArgumentExpressionAt(1); if (secondExpression == null) { continue; } var secondSymbol = context.SemanticModel.GetSymbolInfo(secondExpression).Symbol; if (secondSymbol?.OriginalDefinition?.ContainingType?.Name != nameof(LightParameter)) { continue; } LightParameter secondEnum; if (Enum.TryParse(secondSymbol.Name, out secondEnum)) { var thirdExpression = lightOp.GetArgumentExpressionAt(2); if (thirdExpression == null) { continue; } var typeInfo = context.SemanticModel.GetTypeInfo(thirdExpression); var typeName = typeInfo.Type?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); string[] correctTypeNames = null; switch (secondEnum) { // Color4, Vector4, int[4], float[4] // => Color4, Vector, int[], float[] case LightParameter.Ambient: case LightParameter.Diffuse: case LightParameter.Specular: correctTypeNames = new[] { nameof(OpenTK.Graphics.Color4), nameof(OpenTK.Vector4), "int[]", "float[]" }; break; // Vector4, int[4], float[4] // => Vector4, int[], float[] case LightParameter.Position: case LightParameter.SpotDirection: correctTypeNames = new[] { nameof(OpenTK.Vector4), "int[]", "float[]" }; break; // [0, 128] // => int, float case LightParameter.SpotExponent: correctTypeNames = new[] { "int", "float" }; break; // [0, 90] // => int, float case LightParameter.SpotCutoff: correctTypeNames = new[] { "int", "float" }; break; // int[3], float[3] (non negative) // => int[], float[] case LightParameter.ConstantAttenuation: case LightParameter.LinearAttenuation: case LightParameter.QuadraticAttenuation: correctTypeNames = new[] { "int[]", "float[]" }; break; } if (correctTypeNames.Any(n => n == typeName)) { continue; } context.ReportDiagnostic(Diagnostic.Create( descriptor: Rule, location: thirdExpression.GetLocation(), messageArgs: new[] { nameof(LightParameter) + "." + secondSymbol.Name, string.Join(", ", correctTypeNames) })); } } } }
private Task ProcessCompilationUnitCompleted(CompilationUnitCompletedEvent completedEvent, CancellationToken cancellationToken) { // When the compiler is finished with a compilation unit, we can run user diagnostics which // might want to ask the compiler for all the diagnostics in the source file, for example // to get information about unnecessary usings. try { // Execute analyzers in parallel. var tasks = ArrayBuilder<Task>.GetInstance(); var semanticModel = completedEvent.SemanticModel; foreach (var analyzerAndActions in _semanticModelActionsMap) { var task = Task.Run(() => { // Execute actions for a given analyzer sequentially. foreach (var semanticModelAction in analyzerAndActions.Value) { Debug.Assert(semanticModelAction.Analyzer == analyzerAndActions.Key); // Catch Exception from semanticModelAction AnalyzerDriverHelper.ExecuteAndCatchIfThrows(semanticModelAction.Analyzer, _addDiagnostic, continueOnAnalyzerException, () => { cancellationToken.ThrowIfCancellationRequested(); var semanticModelContext = new SemanticModelAnalysisContext(semanticModel, this.analyzerOptions, _addDiagnostic, cancellationToken); semanticModelAction.Action(semanticModelContext); }, cancellationToken); } }, cancellationToken); tasks.Add(task); } return Task.WhenAll(tasks.ToArrayAndFree()); } finally { completedEvent.FlushCache(); } }
private static async void Analyze(SemanticModelAnalysisContext context) { var root = await context.SemanticModel.SyntaxTree.GetRootAsync(); var invocations = root.DescendantNodes().OfType<InvocationExpressionSyntax>(); var lights = invocations.Where(i => i.GetMethodCallingName() == nameof(GL) + "." + nameof(GL.Light)); var useLights = new bool[8]; var lightLocations = new List<Location>[8]; for (int i = 0; i < lightLocations.Length; i++) { lightLocations[i] = new List<Location>(); } foreach (var lightOp in lights) { var expression = lightOp.GetArgumentExpressionAt(0); if (expression == null) { continue; } var symbol = context.SemanticModel.GetSymbolInfo(expression).Symbol?.OriginalDefinition as IFieldSymbol; if (symbol?.Type?.Name != nameof(LightName)) { continue; } int number; if (symbol.Name.Length > 5 && int.TryParse(symbol.Name.Substring(5), out number) && 0 <= number && number < 8) { useLights[number] = true; lightLocations[number].Add(lightOp.GetLocation()); } } if (!useLights.Any(u => u)) { return; } // need light enabling var enables = invocations.Where(i => i.GetMethodCallingName() == nameof(GL) + "." + nameof(GL.Enable)); var enableLights = new bool[8]; var enableWholeLighting = false; var enableLocations = new List<Location>(); foreach (var enableOp in enables) { var expression = enableOp.GetArgumentExpressionAt(0); if (expression == null) { continue; } var symbol = context.SemanticModel.GetSymbolInfo(expression).Symbol?.OriginalDefinition as IFieldSymbol; if (symbol?.Type?.Name != nameof(EnableCap)) { continue; } if (symbol.Name == nameof(EnableCap.Lighting)) { enableWholeLighting = true; continue; } int number; if (symbol.Name.Length > 5 && int.TryParse(symbol.Name.Substring(5), out number) && 0 <= number && number < 8) { enableLights[number] = true; enableLocations.Add(enableOp.GetLocation()); } } for (int i = 0; i < enableLights.Length; i++) { if (useLights[i] && !enableLights[i]) { foreach (var location in lightLocations[i]) { context.ReportDiagnostic(Diagnostic.Create( descriptor: Rule, location: location, messageArgs: $"{nameof(GL)}.{nameof(GL.Enable)}({nameof(EnableCap)}.Light{i})")); } } } if (!enableWholeLighting) { foreach (var location in enableLocations) { context.ReportDiagnostic(Diagnostic.Create( descriptor: Rule, location: location, messageArgs: $"{nameof(GL)}.{nameof(GL.Enable)}({nameof(EnableCap)}.{nameof(EnableCap.Lighting)})")); } } }
private static async void Analyze(SemanticModelAnalysisContext context) { var root = await context.SemanticModel.SyntaxTree.GetRootAsync(); var invocations = root.DescendantNodes().OfType<InvocationExpressionSyntax>(); var fogs = invocations.Where(i => i.GetMethodCallingName() == nameof(GL) + "." + nameof(GL.Fog)); foreach (var fogOp in fogs) { if (fogOp.ArgumentList.Arguments.Count == 2) { var firstExpression = fogOp.GetArgumentExpressionAt(0); if (firstExpression == null) { continue; } var firstSymbol = context.SemanticModel.GetSymbolInfo(firstExpression).Symbol; if (firstSymbol?.OriginalDefinition.ContainingType?.Name != nameof(FogParameter)) { continue; } FogParameter firstEnum; if (Enum.TryParse(firstSymbol.Name, out firstEnum)) { string[] correctTypeNames = null; bool useFogMode = false; switch (firstEnum) { // *special* // FogMode > Linear, Exp, exp2 (int casted) case FogParameter.FogMode: correctTypeNames = new[] { nameof(FogMode.Linear), nameof(FogMode.Exp), nameof(FogMode.Exp2) }; useFogMode = true; break; // int, float case FogParameter.FogDensity: case FogParameter.FogStart: case FogParameter.FogEnd: case FogParameter.FogIndex: correctTypeNames = new[] { "int", "float" }; break; // int[], float[] case FogParameter.FogColor: correctTypeNames = new[] { "int[]", "float[]" }; break; // *special* // FogMode > FogCoord, FragmentDepth (int casted) case FogParameter.FogCoordSrc: correctTypeNames = new[] { nameof(FogMode.FogCoord), nameof(FogMode.FragmentDepth) }; useFogMode = true; break; } // *special* if (useFogMode) { var expression = fogOp.GetArgumentExpressionAt(1); var castExpression = expression as CastExpressionSyntax; Location location = expression.GetLocation(); if (castExpression != null && castExpression.Type.ToFullString() == "int") { var insideExpression = castExpression.Expression; if (insideExpression == null) { continue; } location = insideExpression.GetLocation(); var typeInfo = context.SemanticModel.GetTypeInfo(insideExpression); if (typeInfo.Type?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) == nameof(FogMode)) { var elementName = insideExpression.DescendantNodesAndSelf().LastOrDefault()?.ToFullString(); if (correctTypeNames.Any(n => n == elementName)) { continue; } } } context.ReportDiagnostic(Diagnostic.Create( descriptor: Rule, location: location, messageArgs: new[] { nameof(FogParameter) + "." + firstSymbol.Name, "int casted " + string.Join(", ", correctTypeNames.Select(n => nameof(FogMode) + "." + n)) })); } else { var secondExpression = fogOp.GetArgumentExpressionAt(1); if (secondExpression == null) { continue; } var typeInfo = context.SemanticModel.GetTypeInfo(secondExpression); var typeName = typeInfo.Type?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); if (correctTypeNames.Any(n => n == typeName)) { continue; } context.ReportDiagnostic(Diagnostic.Create( descriptor: Rule, location: secondExpression.GetLocation(), messageArgs: new[] { nameof(FogParameter) + "." + firstSymbol.Name, string.Join(", ", correctTypeNames) })); } } } } }
/// <summary> /// Emits a diagnostic for <paramref name="syntaxNode" /> using the <paramref name="messageArgs" /> to format the /// diagnostic message. /// </summary> /// <param name="context">The context in which the diagnostic should be emitted.</param> /// <param name="syntaxNode">The syntax node the diagnostic is emitted for.</param> /// <param name="messageArgs">The arguments for formatting the diagnostic message.</param> public void Emit(SemanticModelAnalysisContext context, [NotNull] SyntaxNode syntaxNode, params object[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(syntaxNode.GetLocation(), messageArgs)); }
/// <summary> /// Emits a diagnostic for <paramref name="syntaxToken" /> using the <paramref name="messageArgs" /> to format the /// diagnostic message. /// </summary> /// <param name="context">The context in which the diagnostic should be emitted.</param> /// <param name="syntaxToken">The syntax token the diagnostic is emitted for.</param> /// <param name="messageArgs">The arguments for formatting the diagnostic message.</param> public void Emit(SemanticModelAnalysisContext context, SyntaxToken syntaxToken, params object[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(syntaxToken.GetLocation(), messageArgs)); }
/// <summary> /// Emits a diagnostic for <paramref name="location" /> using the <paramref name="messageArgs" /> to format the /// diagnostic message. /// </summary> /// <param name="context">The context in which the diagnostic should be emitted.</param> /// <param name="location">The location the diagnostic is emitted for.</param> /// <param name="messageArgs">The arguments for formatting the diagnostic message.</param> public void Emit(SemanticModelAnalysisContext context, [NotNull] Location location, params object[] messageArgs) { context.ReportDiagnostic(CreateDiagnostic(location, messageArgs)); }
private static void ReportDiagnostic(SemanticModelAnalysisContext context, AttributeSyntax matchingNode) { context.ReportDiagnostic( Diagnostic.Create(Rule, DetermineDiagnosticTarget(matchingNode).GetLocation(), GetClassName(matchingNode))); }
/// <summary> /// Analyzes a semantic model. /// </summary> /// <param name="context">The context.</param> private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var model = context.SemanticModel; // Look over the object for debugging var inspect = context; // TODO: Tell Alfred }