public static void Analyze(SyntaxNodeAnalysisContext context, NamespaceDeclarationSyntax namespaceDeclaration) { SyntaxList <MemberDeclarationSyntax> members = namespaceDeclaration.Members; SyntaxList <ExternAliasDirectiveSyntax> externs = namespaceDeclaration.Externs; if (externs.Any()) { AnalyzeStart(context, externs.First(), namespaceDeclaration.OpenBraceToken); } else { SyntaxList <UsingDirectiveSyntax> usings = namespaceDeclaration.Usings; if (usings.Any()) { AnalyzeStart(context, usings.First(), namespaceDeclaration.OpenBraceToken); } else if (members.Any()) { AnalyzeStart(context, members.First(), namespaceDeclaration.OpenBraceToken); } } if (members.Any()) { AnalyzeEnd(context, members.Last(), namespaceDeclaration.CloseBraceToken); } }
private static void AnalyzeNamespaceDeclaration(SyntaxNodeAnalysisContext context) { var namespaceDeclaration = (NamespaceDeclarationSyntax)context.Node; SyntaxList <MemberDeclarationSyntax> members = namespaceDeclaration.Members; SyntaxList <ExternAliasDirectiveSyntax> externs = namespaceDeclaration.Externs; if (externs.Any()) { AnalyzeStart(context, externs[0], namespaceDeclaration.OpenBraceToken); } else { SyntaxList <UsingDirectiveSyntax> usings = namespaceDeclaration.Usings; if (usings.Any()) { AnalyzeStart(context, usings[0], namespaceDeclaration.OpenBraceToken); } else if (members.Any()) { AnalyzeStart(context, members[0], namespaceDeclaration.OpenBraceToken); } } if (members.Any()) { AnalyzeEnd(context, members.Last(), namespaceDeclaration.CloseBraceToken); } }
private static bool HasThreadStaticAttribute(SyntaxList <AttributeListSyntax> attributeLists, SemanticModel semanticModel) { if (!attributeLists.Any()) { return(false); } return(attributeLists.Any(attributeList => attributeList.Attributes.Any(attribute => semanticModel.GetTypeInfo(attribute).Type.Is(KnownType.System_ThreadStaticAttribute)))); }
private static bool HasThreadStaticAttribute(SyntaxList <AttributeListSyntax> attributeLists, SemanticModel semanticModel) { if (!attributeLists.Any()) { return(false); } return(attributeLists .Any(attributeList => attributeList.Attributes .Select(attribute => semanticModel.GetTypeInfo(attribute).Type) .Any(attributeType => attributeType != null && attributeType.ToDisplayString() == ThreadStaticAttributeName))); }
private static PatternSyntax GetPattern(SyntaxList <SwitchLabelSyntax> switchLabels, out WhenClauseSyntax whenClauseOpt) { if (switchLabels.Count == 1) { return(GetPattern(switchLabels[0], out whenClauseOpt)); } if (switchLabels.Any(label => IsDefaultSwitchLabel(label))) { // original group had a catch-all label. just convert to a discard _ to indicate the same. whenClauseOpt = null; return(DiscardPattern()); } // Multiple labels, and no catch-all merge them using an 'or' pattern. var totalPattern = GetPattern(switchLabels[0], out var whenClauseUnused); Debug.Assert(whenClauseUnused == null, "We should not have offered to convert multiple cases if any have a when clause"); for (var i = 1; i < switchLabels.Count; i++) { var nextPatternPart = GetPattern(switchLabels[i], out whenClauseUnused); Debug.Assert(whenClauseUnused == null, "We should not have offered to convert multiple cases if any have a when clause"); totalPattern = BinaryPattern(SyntaxKind.OrPattern, totalPattern.Parenthesize(), nextPatternPart.Parenthesize()); } whenClauseOpt = null; return(totalPattern); }
internal static bool IsFixable(IfStatementSyntax ifStatement) { if (ifStatement == null) { return(false); } if (!ifStatement.IsSimpleIf()) { return(false); } if (ifStatement.Condition?.IsMissing != false) { return(false); } if (!(ifStatement.Statement is BlockSyntax block)) { return(false); } SyntaxList <StatementSyntax> statements = block.Statements; if (!statements.Any()) { return(false); } return(statements.Count > 1 || GetJumpKind(statements.First()) == SyntaxKind.None); }
private void AnalyzerNamespaceDeclaration(SyntaxNodeAnalysisContext context) { if (GeneratedCodeAnalyzer?.IsGeneratedCode(context) == true) { return; } var declaration = (NamespaceDeclarationSyntax)context.Node; if (declaration.Members.Count == 0 && !declaration.OpenBraceToken.IsMissing && !declaration.CloseBraceToken.IsMissing && declaration.OpenBraceToken.TrailingTrivia.All(f => f.IsWhitespaceOrEndOfLineTrivia()) && declaration.CloseBraceToken.LeadingTrivia.All(f => f.IsWhitespaceOrEndOfLineTrivia())) { context.ReportDiagnostic( DiagnosticDescriptors.RemoveEmptyNamespaceDeclaration, declaration.GetLocation()); } SyntaxList <UsingDirectiveSyntax> usings = declaration.Usings; if (usings.Any()) { context.ReportDiagnostic( DiagnosticDescriptors.DeclareUsingDirectiveOnTopLevel, Location.Create(declaration.SyntaxTree, usings.Span)); } }
private static void AnalyzeSwitchSection(SyntaxNodeAnalysisContext context) { var switchSection = (SwitchSectionSyntax)context.Node; if (!switchSection.IsParentKind(SyntaxKind.SwitchStatement)) { return; } SyntaxList <SwitchLabelSyntax> labels = switchSection.Labels; if (labels.Count <= 1) { return; } if (!labels.Any(SyntaxKind.DefaultSwitchLabel)) { return; } foreach (SwitchLabelSyntax label in labels) { if (!label.IsKind(SyntaxKind.DefaultSwitchLabel) && label.Keyword.TrailingTrivia.IsEmptyOrWhitespace() && label.ColonToken.LeadingTrivia.IsEmptyOrWhitespace()) { DiagnosticHelpers.ReportDiagnostic(context, DiagnosticRules.RemoveUnnecessaryCaseLabel, label); } } }
private static IfStatementSyntax CreateNullCheck(ExpressionSyntax expression, SyntaxList <StatementSyntax> statements = default(SyntaxList <StatementSyntax>)) { SyntaxToken openBrace = (statements.Any()) ? OpenBraceToken() : Token(default(SyntaxTriviaList), SyntaxKind.OpenBraceToken, TriviaList(NewLine())); SyntaxToken closeBrace = (statements.Any()) ? CloseBraceToken() : Token(TriviaList(NewLine()), SyntaxKind.CloseBraceToken, default(SyntaxTriviaList)); IfStatementSyntax ifStatement = IfStatement( NotEqualsExpression(expression.WithoutTrivia(), NullLiteralExpression()), Block(openBrace, statements, closeBrace)); return(ifStatement.WithFormatterAnnotation()); }
private static AwaitExpressionSyntax GetLastReturnAwaitExpressionOfDefault(StatementSyntax statement) { if (statement != null) { SyntaxKind kind = statement.Kind(); if (kind == SyntaxKind.Block) { var block = (BlockSyntax)statement; SyntaxList <StatementSyntax> statements = block.Statements; if (statements.Any()) { StatementSyntax last = statements.Last(); if (last.IsKind(SyntaxKind.ReturnStatement)) { return(((ReturnStatementSyntax)last).Expression as AwaitExpressionSyntax); } } } else if (kind == SyntaxKind.ReturnStatement) { return(((ReturnStatementSyntax)statement).Expression as AwaitExpressionSyntax); } } return(null); }
public static void Analyze(SyntaxNodeAnalysisContext context, SwitchStatementSyntax switchStatement) { SyntaxList <SwitchSectionSyntax> sections = switchStatement.Sections; if (sections.Any()) { AnalyzeStart(context, sections.First(), switchStatement.OpenBraceToken); AnalyzeEnd(context, sections.Last(), switchStatement.CloseBraceToken); if (sections.Count > 1) { SwitchSectionSyntax prevSection = sections.First(); for (int i = 1; i < sections.Count; i++) { if (prevSection.Statements.LastOrDefault()?.IsKind(SyntaxKind.Block) == true) { Analyze(context, prevSection, sections[i]); } prevSection = sections[i]; } } } }
private SyntaxList <StatementSyntax> CreateConditionFunc(SyntaxList <StatementSyntax> statements, bool type, int ifCounter, List <string> mappedVariables) { SyntaxList <StatementSyntax> newStatements = new SyntaxList <StatementSyntax>(); StatementSyntax ifReturnStatement = null; SyntaxList <StatementSyntax> variableMapping = new SyntaxList <StatementSyntax>(mappedVariables.Select(e => SyntaxFactory.ParseStatement($"var _{e} = {e};"))); var templateSignature = $"Func<Tuple<{string.Join(", ", Enumerable.Repeat("AutoTFOutput", Math.Max(mappedVariables.Count, 1)))}>>"; var ifTrueStatement = SyntaxFactory.ParseStatement($"{templateSignature} if{type}{ifCounter} = () => {{"); if (!statements.Any(e => { return(e.IsKind(SyntaxKind.ReturnStatement)); })) { if (mappedVariables.Count > 0) { ifReturnStatement = SyntaxFactory.ParseStatement($"return Tuple.Create({GetReturnVariablesString(mappedVariables, "_")});"); } else { ifReturnStatement = SyntaxFactory.ParseStatement($"return new AutoTFOutput(session.Graph.Const(1), session);"); } } newStatements = newStatements.Add(ifTrueStatement); newStatements = newStatements.AddRange(variableMapping); newStatements = newStatements.AddRange(ReplaceVariables(statements, mappedVariables)); newStatements = newStatements.Add(ifReturnStatement); newStatements = newStatements.Add(SyntaxFactory.ParseStatement("};")); return(newStatements); }
public static void AnalyzeBlock(SyntaxNodeAnalysisContext context) { var block = (BlockSyntax)context.Node; if (!(block.Parent is AccessorDeclarationSyntax) && !(block.Parent is AnonymousFunctionExpressionSyntax)) { SyntaxList <StatementSyntax> statements = block.Statements; if (statements.Any()) { SyntaxToken openBrace = block.OpenBraceToken; if (!openBrace.IsMissing) { SyntaxToken closeBrace = block.CloseBraceToken; if (!closeBrace.IsMissing && block.SyntaxTree.IsSingleLineSpan(TextSpan.FromBounds(openBrace.SpanStart, closeBrace.Span.End), context.CancellationToken)) { context.ReportDiagnostic(DiagnosticDescriptors.AvoidSingleLineBlock, block); } } } } }
private void AnalyzeBlock(SyntaxNodeAnalysisContext context) { if (GeneratedCodeAnalyzer?.IsGeneratedCode(context) == true) { return; } var block = (BlockSyntax)context.Node; RedundantEmptyLineAnalyzer.AnalyzeBlock(context, block); SyntaxList <StatementSyntax> statements = block.Statements; FormatEachStatementOnSeparateLineAnalyzer.AnalyzeStatements(context, statements); if (!statements.Any()) { int startLine = block.OpenBraceToken.GetSpanStartLine(); int endLine = block.CloseBraceToken.GetSpanEndLine(); if ((endLine - startLine) != 1 && block .DescendantTrivia(block.Span) .All(f => f.IsWhitespaceOrEndOfLineTrivia())) { context.ReportDiagnostic(DiagnosticDescriptors.FormatEmptyBlock, block.GetLocation()); } } }
private static Task <Document> WrapBaseListAsync( Document document, BaseListSyntax baseList, CancellationToken cancellationToken = default) { List <TextChange> textChanges = GetFixListChanges( baseList, baseList.ColonToken, baseList.Types, ListFixMode.Wrap, cancellationToken); if (baseList.Types.Count > 1) { GenericInfo genericInfo = SyntaxInfo.GenericInfo(baseList.Parent); SyntaxList <TypeParameterConstraintClauseSyntax> constraintClauses = genericInfo.ConstraintClauses; if (constraintClauses.Any()) { List <TextChange> textChanges2 = GetFixListChanges( genericInfo.Node, constraintClauses.First().WhereKeyword.GetPreviousToken(), constraintClauses, ListFixMode.Wrap, cancellationToken); textChanges.AddRange(textChanges2); } } return(document.WithTextChangesAsync(textChanges, cancellationToken)); }
public static async Task <Document> RefactorAsync( Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(methodDeclaration.ReturnType, cancellationToken); int position = -1; BlockSyntax body = methodDeclaration.Body; SyntaxList <StatementSyntax> statements = body.Statements; if (statements.Any()) { position = statements.Last().FullSpan.End; } else { position = body.OpenBraceToken.FullSpan.End; } MethodDeclarationSyntax newNode = methodDeclaration .AddBodyStatements(ReturnStatement(typeSymbol.ToDefaultExpression(semanticModel, position))); return(await document.ReplaceNodeAsync(methodDeclaration, newNode, cancellationToken).ConfigureAwait(false)); }
/// <summary> /// Verifies whether attributeLists contain a test-case attribute /// </summary> /// <param name="attributeLists">List of AttributeListSyntax</param> /// <returns>True if attributeLists contain a test-case attribute, or False</returns> public static bool IsTestAttribute(SyntaxList <AttributeListSyntax> attributeLists) { return(attributeLists.Any(attributeList => { return attributeList.Attributes.Any(attribute => attribute.Name.ToString().Equals("TestFixture")); })); }
public static SelectionResult Create <TNode>(SyntaxList <TNode> nodes, TextSpan span, int minCount, int maxCount) where TNode : SyntaxNode { ThrowIfNotValidRange(minCount, maxCount); if (!nodes.Any()) { return(Fail); } if (span.IsEmpty) { return(Fail); } SelectionResult result = Create(nodes, span); if (!result.Success) { return(Fail); } if (!result.IsInRange(minCount, maxCount)) { return(Fail); } return(result); }
protected override (ExpressionSyntax expression, SyntaxList <StatementSyntax> statements) GetExpressionOrStatements(MethodDeclarationSyntax declaration) { BlockSyntax body = declaration.Body; if (body == null) { return(declaration.ExpressionBody?.Expression, default(SyntaxList <StatementSyntax>)); } SyntaxList <StatementSyntax> statements = body.Statements; if (!statements.Any()) { return(null, default(SyntaxList <StatementSyntax>)); } switch (statements.SingleOrDefault(shouldThrow: false)) { case ReturnStatementSyntax returnStatement: return(returnStatement.Expression, default(SyntaxList <StatementSyntax>)); case ExpressionStatementSyntax expressionStatement: return(expressionStatement.Expression, default(SyntaxList <StatementSyntax>)); } if (!declaration.ReturnsVoid()) { return(null, default(SyntaxList <StatementSyntax>)); } return(null, statements); }
private static bool CanRemoveNewLinesFromAccessor(AccessorDeclarationSyntax accessor) { BlockSyntax body = accessor.Body; if (body != null) { SyntaxList <StatementSyntax> statements = body.Statements; if (statements.Count <= 1 && accessor.SyntaxTree.IsMultiLineSpan(TextSpan.FromBounds(accessor.Keyword.SpanStart, accessor.Span.End)) && (!statements.Any() || statements[0].IsSingleLine())) { return(accessor .DescendantTrivia(accessor.Span, descendIntoTrivia: true) .All(f => f.IsWhitespaceOrEndOfLineTrivia())); } } else { ArrowExpressionClauseSyntax expressionBody = accessor.ExpressionBody; if (expressionBody != null && accessor.SyntaxTree.IsMultiLineSpan(TextSpan.FromBounds(accessor.Keyword.SpanStart, accessor.Span.End)) && expressionBody.Expression?.IsSingleLine() == true) { return(accessor .DescendantTrivia(accessor.Span, descendIntoTrivia: true) .All(f => f.IsWhitespaceOrEndOfLineTrivia())); } } return(false); }
private static void AnalyzeSwitchStatement(SyntaxNodeAnalysisContext context) { var switchStatement = (SwitchStatementSyntax)context.Node; SyntaxList <SwitchSectionSyntax> sections = switchStatement.Sections; if (sections.Any()) { AnalyzeStart(context, sections[0], switchStatement.OpenBraceToken); AnalyzeEnd(context, sections.Last(), switchStatement.CloseBraceToken); if (sections.Count > 1 && !context.IsAnalyzerSuppressed(AnalyzerOptions.RemoveEmptyLineBetweenClosingBraceAndSwitchSection)) { SwitchSectionSyntax prevSection = sections[0]; for (int i = 1; i < sections.Count; i++) { SwitchSectionSyntax section = sections[i]; if (prevSection.Statements.LastOrDefault() is BlockSyntax block) { Analyze(context, block.CloseBraceToken, section); } prevSection = section; } } } }
private static AwaitExpressionSyntax GetLastReturnAwaitExpressionOfDefault(StatementSyntax statement) { if (statement != null) { SyntaxKind kind = statement.Kind(); if (kind == SyntaxKind.Block) { var block = (BlockSyntax)statement; SyntaxList <StatementSyntax> statements = block.Statements; if (statements.Any()) { for (int i = 0; i < statements.Count - 1; i++) { if (!statements[i].IsKind(SyntaxKind.LocalFunctionStatement) && ContainsAwaitExpression(statements[i])) { return(null); } } return(GetAwaitExpressionOrDefault(statements.Last())); } } else if (kind == SyntaxKind.ReturnStatement) { return(GetAwaitExpressionOrDefault((ReturnStatementSyntax)statement)); } } return(null); }
private static SyntaxList <StatementSyntax> AddBreakStatementIfNecessary(StatementSyntax statement) { if (statement.IsKind(SyntaxKind.Block)) { var block = (BlockSyntax)statement; SyntaxList <StatementSyntax> statements = block.Statements; if (statements.Any() && IsJumpStatement(statements.Last())) { return(SingletonList <StatementSyntax>(block)); } else { return(SingletonList <StatementSyntax>(block.AddStatements(BreakStatement()))); } } else { if (IsJumpStatement(statement)) { return(SingletonList(statement)); } else { return(SingletonList <StatementSyntax>(Block(statement, BreakStatement()))); } } }
private static void AnalyzeTryStatement(SyntaxNodeAnalysisContext context) { var tryStatement = (TryStatementSyntax)context.Node; BlockSyntax block = tryStatement.Block; if (block != null) { SyntaxList <CatchClauseSyntax> catches = tryStatement.Catches; if (catches.Any()) { SyntaxNode previousNode = block; foreach (CatchClauseSyntax catchClause in catches) { Analyze(context, previousNode, catchClause); previousNode = catchClause; } FinallyClauseSyntax finallyClause = tryStatement.Finally; if (finallyClause != null) { Analyze(context, previousNode, finallyClause); } } } }
private static void AnalyzeSwitchSection(SyntaxNodeAnalysisContext context) { var switchSection = (SwitchSectionSyntax)context.Node; SyntaxList <StatementSyntax> statements = switchSection.Statements; if (!statements.Any()) { return; } SyntaxList <SwitchLabelSyntax> labels = switchSection.Labels; if (!labels.Any()) { return; } StatementSyntax statement = statements[0]; if (!switchSection.SyntaxTree.IsSingleLineSpan(TextSpan.FromBounds(labels.Last().Span.End, statement.SpanStart))) { return; } DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.AddNewLineAfterSwitchLabel, statement); }
public static bool TryCreate(StatementsInfo statementsInfo, TextSpan span, out StatementsSelection selectedStatements) { selectedStatements = null; if (span.IsEmpty) { return(false); } SyntaxList <StatementSyntax> statements = statementsInfo.Statements; if (!statements.Any()) { return(false); } (int startIndex, int endIndex) = GetIndexes(statements, span); if (startIndex == -1) { return(false); } selectedStatements = new StatementsSelection(statementsInfo, span, startIndex, endIndex); return(true); }
private static SyntaxList <TypeParameterConstraintClauseSyntax> GetNewConstraintClause( SyntaxList <TypeParameterConstraintClauseSyntax> constraintClauses, string typeParameterName) { if (!constraintClauses.Any()) { return(constraintClauses); } var constraintList = SyntaxFactory.List <TypeParameterConstraintClauseSyntax>(); foreach (var constraint in constraintClauses) { var currentConstraint = constraint; if (constraint.Name.Identifier.ValueText == typeParameterName) { currentConstraint = currentConstraint .WithConstraints( currentConstraint.Constraints.Insert(0, SyntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint))) .WithAdditionalAnnotations(Formatter.Annotation); } constraintList = constraintList.Add(currentConstraint); } return(constraintList); }
private static bool TryGetThreadStaticAttribute(SyntaxList <AttributeListSyntax> attributeLists, SemanticModel semanticModel, out AttributeSyntax threadStaticAttribute) { threadStaticAttribute = null; if (!attributeLists.Any()) { return(false); } foreach (var attributeList in attributeLists) { foreach (var attribute in attributeList.Attributes) { var attributeType = semanticModel.GetTypeInfo(attribute).Type; if (attributeType != null && attributeType.ToDisplayString() == ThreadStaticAttributeName) { threadStaticAttribute = attribute; return(true); } } } return(false); }
internal static bool IsFixableRecursively(IfStatementSyntax ifStatement, SyntaxKind jumpKind) { if (!(ifStatement.Statement is BlockSyntax block)) { return(false); } SyntaxList <StatementSyntax> statements = block.Statements; if (!statements.Any()) { return(false); } StatementSyntax statement = statements.Last(); if (statement is IfStatementSyntax ifStatement2) { return(IsFixable(ifStatement2)); } return(jumpKind == GetJumpKind(statement) && (statements.LastButOneOrDefault() is IfStatementSyntax ifStatement3) && IsFixable(ifStatement3)); }
public static void AnalyzeTypeParameterList(SyntaxNodeAnalysisContext context) { var typeParameterList = (TypeParameterListSyntax)context.Node; SeparatedSyntaxList <TypeParameterSyntax> typeParameters = typeParameterList.Parameters; if (!typeParameters.Any()) { return; } SyntaxList <TypeParameterConstraintClauseSyntax> constraintClauses = GetConstraintClauses(typeParameterList.Parent); if (!constraintClauses.Any()) { return; } if (constraintClauses.SpanContainsDirectives()) { return; } if (!IsFixable(typeParameters, constraintClauses)) { return; } context.ReportDiagnostic( DiagnosticDescriptors.ReorderTypeParameterConstraints, constraintClauses.First()); }