SwitchInformation GetInformationAboutSwitch(SemanticModel model, SwitchStatementSyntax node, CancellationToken ct) { try { SwitchInformation info = new SwitchInformation(); var type = model.GetTypeInfo(node.Expression, ct).Type; if (isEnum(type)) { var defaults = node.Sections.SelectMany(s => s.Labels).OfType <DefaultSwitchLabelSyntax>().ToArray(); info.HasDefault = defaults.Any(); if (info.HasDefault) { var d = defaults.First(); var first = ((SwitchSectionSyntax)d.Parent).Statements.FirstOrDefault(); info.DefaultIsThrow = first is ThrowStatementSyntax; } info.NotFoundSymbolNames = GetUnusedSymbolNames(model, node, type, ct); return(info); } } catch (Exception) { // ignored } return(null); }
private void Analyze(SyntaxNodeAnalysisContext context) { if (context.Node is SwitchStatementSyntax switchSyntax) { SwitchInformation information = GetInformationAboutSwitch(context.SemanticModel, switchSyntax, context.CancellationToken); if (information is SwitchInformation) { if (information.NotExhaustiveSwitch) { var diagnostic = Diagnostic.Create(NotExhaustiveSwitchRule, switchSyntax.Expression.GetLocation(), string.Join("\n", information.NotFoundSymbolNames)); context.ReportDiagnostic(diagnostic); } else if (information.UnreachableDefault) { var diagnostic = Diagnostic.Create(DefaultUnreachableRule, switchSyntax.Expression.GetLocation()); context.ReportDiagnostic(diagnostic); } } } }