public static ElseClauseSyntax AddBraces(ElseClauseSyntax elseClause) { Debug.Assert(elseClause != null && NeedsBraces(elseClause)); return elseClause .WithStatement(SyntaxFactory.Block(elseClause.Statement)) .WithAdditionalAnnotations(Formatter.Annotation); }
private void HandleElse(SyntaxNodeAnalysisContext context, ElseClauseSyntax elseClause) { if (elseClause.Statement is BlockSyntax) { return; } context.ReportDiagnostic(Diagnostic.Create(Rule, elseClause.ElseKeyword.GetLocation())); }
public override SyntaxNode VisitElseClause(ElseClauseSyntax node) { if (node.Statement is IfStatementSyntax) return base.VisitElseClause(node); SyntaxNode rewrittenNode = null; if (node.Statement != null) rewrittenNode = RewriteWithBlockIfRequired(node, node.Statement); return base.VisitElseClause((ElseClauseSyntax)rewrittenNode ?? node); }
public override SyntaxNode VisitElseClause(ElseClauseSyntax node) { node = (ElseClauseSyntax)base.VisitElseClause(node); if (node.Statement.Kind == SyntaxKind.Block || node.Statement.Kind == SyntaxKind.IfStatement) { return node; } var block = Syntax.Block(statements: Syntax.List(node.Statement)); return Syntax.ElseClause( node.ElseKeyword, block); }
public override void VisitElseClause(ElseClauseSyntax node) { if (node.Statement is IfStatementSyntax) { base.VisitElseClause(node); return; } if (!(node.Statement is BlockSyntax)) { CreateAuditVariable(node.Statement); } base.VisitElseClause(node); }
public override SyntaxNode VisitElseClause(ElseClauseSyntax node) { node = (ElseClauseSyntax)base.VisitElseClause(node); if (node.Statement.Kind != SyntaxKind.Block) { return CodeAnnotations.Formatting.AddAnnotationTo( Syntax.ElseClause( node.ElseKeyword, WrapStatementWithBlock(node.Statement))); } else { return node; } }
public override void VisitElseClause(ElseClauseSyntax node) { IfStatementSyntax ifNode = node.Statement as IfStatementSyntax; if (null != ifNode) { CodeBuilder.AppendFormat("{0}}}elseif( ", GetIndentString()); var oper = m_Model.GetOperationEx(node) as IConditionalOperation; IConversionOperation opd = null; if (null != oper) { opd = oper.Condition as IConversionOperation; } OutputExpressionSyntax(ifNode.Condition, opd); CodeBuilder.AppendLine(" ){"); ++m_Indent; ifNode.Statement.Accept(this); --m_Indent; if (null != ifNode.Else) { VisitElseClause(ifNode.Else); } else { CodeBuilder.AppendFormat("{0}}};", GetIndentString()); CodeBuilder.AppendLine(); } } else { CodeBuilder.AppendFormat("{0}}}else{{", GetIndentString()); CodeBuilder.AppendLine(); ++m_Indent; node.Statement.Accept(this); --m_Indent; CodeBuilder.AppendFormat("{0}}};", GetIndentString()); CodeBuilder.AppendLine(); } }
public override ICodeContext CreateContext(CodeContextTypes contextType, string name = null, Bag <string> attributes = null) { switch (contextType) { case CodeContextTypes.Argument: return(new ExpressionContext((expression) => { if (expression == null) { _condition = SF.LiteralExpression(SyntaxKind.FalseKeyword); } else { _condition = expression.ToExpression(); } })); case CodeContextTypes.ElseIf: return(new IfContext(name, (ifStatement) => { _elseClause = SF.ElseClause(ifStatement); })); case CodeContextTypes.Else: string elseHookName = name; return(new BlockContext((block) => { if (elseHookName == null) { _elseClause = SF.ElseClause(block); } else { _elseClause = SF.ElseClause(BlockContext.MakeWriteStatement(MethodCallContext.CreateMethodCall(elseHookName, true))); } })); } return(base.CreateContext(contextType, name, attributes)); }
private static async Task <Document> RemoveEmptyElseClauseAsync( Document document, ElseClauseSyntax elseClause, CancellationToken cancellationToken) { if (elseClause.IsParentKind(SyntaxKind.IfStatement)) { var ifStatement = (IfStatementSyntax)elseClause.Parent; StatementSyntax statement = ifStatement.Statement; if (statement?.GetTrailingTrivia().IsEmptyOrWhitespace() == true) { IfStatementSyntax newIfStatement = ifStatement .WithStatement(statement.WithTrailingTrivia(elseClause.GetTrailingTrivia())) .WithElse(null); return(await document.ReplaceNodeAsync(ifStatement, newIfStatement, cancellationToken).ConfigureAwait(false)); } } return(await document.RemoveNodeAsync(elseClause, SyntaxRemoveOptions.KeepExteriorTrivia, cancellationToken).ConfigureAwait(false)); }
public static Doc Print(ElseClauseSyntax node) { var docs = new List <Doc> { Token.Print(node.ElseKeyword) }; var statement = Node.Print(node.Statement); if (node.Statement is BlockSyntax) { docs.Add(statement); } else if (node.Statement is IfStatementSyntax) { docs.Add(" ", statement); } else { docs.Add(Doc.Indent(Doc.HardLine, statement)); } return(Doc.Concat(docs)); }
private static bool IsFixableIfElseInsideWhile( IfStatementSyntax ifStatement, ElseClauseSyntax elseClause) { if (elseClause.SingleNonBlockStatementOrDefault()?.Kind() != SyntaxKind.BreakStatement) { return(false); } SyntaxNode parent = ifStatement.Parent; if (parent is BlockSyntax block) { if (block.Statements.Count != 1) { return(false); } parent = block.Parent; } if (!(parent is WhileStatementSyntax whileStatement)) { return(false); } if (whileStatement.SpanContainsDirectives()) { return(false); } if (whileStatement.Condition?.WalkDownParentheses().Kind() != SyntaxKind.TrueLiteralExpression) { return(false); } return(true); }
private static bool CheckTrivia(ElseClauseSyntax elseClause) { if (elseClause.ElseKeyword.TrailingTrivia.Any(f => !f.IsWhitespaceOrEndOfLine())) { return(false); } var block = (BlockSyntax)elseClause.Statement; if (block.OpenBraceToken.LeadingTrivia.Any(f => !f.IsWhitespaceOrEndOfLine())) { return(false); } if (block.OpenBraceToken.TrailingTrivia.Any(f => !f.IsWhitespaceOrEndOfLine())) { return(false); } var ifStatement = (IfStatementSyntax)block.Statements[0]; if (ifStatement.IfKeyword.LeadingTrivia.Any(f => !f.IsWhitespaceOrEndOfLine())) { return(false); } if (ifStatement.GetTrailingTrivia().Any(f => !f.IsWhitespaceOrEndOfLine())) { return(false); } if (block.CloseBraceToken.LeadingTrivia.Any(f => !f.IsWhitespaceOrEndOfLine())) { return(false); } return(true); }
public static async Task <Document> RefactorAsync( Document document, IfStatementSyntax ifStatement, CancellationToken cancellationToken = default(CancellationToken)) { ElseClauseSyntax elseClause = ifStatement.Else; StatementSyntax whenTrue = ifStatement.Statement; StatementSyntax whenFalse = elseClause.Statement; SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); IfStatementSyntax newIfStatement = ifStatement.Update( ifKeyword: ifStatement.IfKeyword, openParenToken: ifStatement.OpenParenToken, condition: Negator.LogicallyNegate(ifStatement.Condition, semanticModel, cancellationToken), closeParenToken: ifStatement.CloseParenToken, statement: whenFalse.WithTriviaFrom(whenTrue), @else: elseClause.WithStatement(whenTrue.WithTriviaFrom(whenFalse))); newIfStatement = newIfStatement.WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(ifStatement, newIfStatement, cancellationToken).ConfigureAwait(false)); }
public static void Analyze(SyntaxNodeAnalysisContext context, ElseClauseSyntax elseClause) { SyntaxNode parent = elseClause.Parent; if (parent?.IsKind(SyntaxKind.IfStatement) == true) { var ifStatement = (IfStatementSyntax)parent; StatementSyntax statement = ifStatement.Statement; if (statement != null) { Analyze(context, statement, elseClause); } statement = elseClause.Statement; if (statement != null) { Analyze(context, elseClause.ElseKeyword, statement); } } }
private static Task <Document> RefactorAsync( Document document, IfStatementSyntax ifStatement, StatementContainerSelection selectedStatements, CancellationToken cancellationToken) { IfStatement ifElse = IfStatement.Create(ifStatement); StatementSyntax newStatement = null; if (selectedStatements.Count == 1 && !ifElse.Nodes.Any(f => f.Statement?.IsKind(SyntaxKind.Block) == true)) { newStatement = selectedStatements.First(); } else { newStatement = SyntaxFactory.Block(selectedStatements); } ElseClauseSyntax elseClause = SyntaxFactory.ElseClause(newStatement).WithFormatterAnnotation(); IfStatementSyntax lastIfStatement = ifElse.Nodes.Last(); IfStatementSyntax newIfStatement = ifStatement.ReplaceNode( lastIfStatement, lastIfStatement.WithElse(elseClause)); SyntaxList <StatementSyntax> newStatements = selectedStatements.Statements.Replace(ifStatement, newIfStatement); for (int i = newStatements.Count - 1; i >= selectedStatements.StartIndex; i--) { newStatements = newStatements.RemoveAt(i); } return(document.ReplaceNodeAsync(selectedStatements.Container.Node, selectedStatements.Container.NodeWithStatements(newStatements), cancellationToken)); }
private static ImmutableArray <IfRefactoring> Analyze( LocalDeclarationStatementSyntax localDeclarationStatement, IfStatementSyntax ifStatement, IfAnalysisOptions options) { VariableDeclaratorSyntax declarator = localDeclarationStatement.Declaration?.SingleVariableOrDefault(); if (declarator != null) { ElseClauseSyntax elseClause = ifStatement.Else; if (elseClause?.Statement?.IsKind(SyntaxKind.IfStatement) == false) { SimpleAssignmentStatement assignment1; if (SimpleAssignmentStatement.TryCreate(ifStatement.GetSingleStatementOrDefault(), out assignment1)) { SimpleAssignmentStatement assignment2; if (SimpleAssignmentStatement.TryCreate(elseClause.GetSingleStatementOrDefault(), out assignment2) && assignment1.Left.IsKind(SyntaxKind.IdentifierName) && assignment2.Left.IsKind(SyntaxKind.IdentifierName)) { string identifier1 = ((IdentifierNameSyntax)assignment1.Left).Identifier.ValueText; string identifier2 = ((IdentifierNameSyntax)assignment2.Left).Identifier.ValueText; if (string.Equals(identifier1, identifier2, StringComparison.Ordinal) && string.Equals(identifier1, declarator.Identifier.ValueText, StringComparison.Ordinal) && options.CheckSpanDirectives(ifStatement.Parent, TextSpan.FromBounds(localDeclarationStatement.SpanStart, ifStatement.Span.End))) { return(new LocalDeclarationAndIfElseAssignmentWithConditionalExpression(localDeclarationStatement, ifStatement, assignment1.Right, assignment2.Right).ToImmutableArray()); } } } } } return(ImmutableArray <IfRefactoring> .Empty); }
public override SyntaxList <VB.Syntax.StatementSyntax> VisitIfStatement(CS.Syntax.IfStatementSyntax node) { VB.Syntax.IfStatementSyntax ifStatement = VB.SyntaxFactory.IfStatement( VB.SyntaxFactory.Token(VB.SyntaxKind.IfKeyword), nodeVisitor.VisitExpression(node.Condition), VB.SyntaxFactory.Token(VB.SyntaxKind.ThenKeyword)); List <VB.Syntax.ElseIfBlockSyntax> elseIfBlocks = new List <VB.Syntax.ElseIfBlockSyntax>(); ElseClauseSyntax currentElseClause = node.Else; while (currentElseClause != null) { if (!currentElseClause.Statement.IsKind(CS.SyntaxKind.IfStatement)) { break; } IfStatementSyntax nestedIf = (CS.Syntax.IfStatementSyntax)currentElseClause.Statement; currentElseClause = nestedIf.Else; VB.Syntax.ElseIfStatementSyntax elseIfStatement = VB.SyntaxFactory.ElseIfStatement( VB.SyntaxFactory.Token(VB.SyntaxKind.ElseIfKeyword), nodeVisitor.VisitExpression(nestedIf.Condition), VB.SyntaxFactory.Token(VB.SyntaxKind.ThenKeyword)); VB.Syntax.ElseIfBlockSyntax elseIfBlock = VB.SyntaxFactory.ElseIfBlock( elseIfStatement, Visit(nestedIf.Statement)); elseIfBlocks.Add(elseIfBlock); } return(List <VB.Syntax.StatementSyntax>( VB.SyntaxFactory.MultiLineIfBlock( ifStatement, Visit(node.Statement), List <VB.Syntax.ElseIfBlockSyntax>(elseIfBlocks), currentElseClause == null ? null : nodeVisitor.Visit <VB.Syntax.ElseBlockSyntax>(currentElseClause)))); }
public static void AddElseToIfBlock() { //get current block BlockSyntax block = Root.DescendantNodes().OfType <BlockSyntax>().Where(n => n.HasAnnotation(CurrentBlock)).Single(); if (!(block.Parent is IfStatementSyntax)) { return; } SyntaxAnnotation syntaxAnnotation = new SyntaxAnnotation("Block", "else"); BlockSyntax elseBlock = SyntaxFactory.Block().WithAdditionalAnnotations(syntaxAnnotation); ElseClauseSyntax elseClauseSyntax = SyntaxFactory.ElseClause(elseBlock); //get if statement IfStatementSyntax oldIfStatement = block.Parent as IfStatementSyntax; //add an empty else block IfStatementSyntax newIfStatement = oldIfStatement.WithElse(elseClauseSyntax); //do the replacement Root = Root.ReplaceNode(oldIfStatement, newIfStatement); //the else block is now current SetBlockAsCurrent(elseBlock); }
/// <summary> /// コンストラクタ /// </summary> /// <param name="node">対象Node</param> /// <param name="semanticModel">対象ソースのsemanticModel</param> /// <param name="parent">親IAnalyzeItem</param> /// <param name="container">イベントコンテナ</param> public ItemElseClause(ElseClauseSyntax node, SemanticModel semanticModel, IAnalyzeItem parent, EventContainer container) : base(parent, node, semanticModel, container) { ItemType = ItemTypes.MethodStatement; if (node.Statement is IfStatementSyntax ifNode) { var condition = semanticModel.GetOperation(ifNode.Condition); Conditions.AddRange(OperationFactory.GetExpressionList(condition, container)); var block = ifNode.Statement as BlockSyntax; foreach (var statement in block.Statements) { Block.Add(ItemFactory.Create(statement, semanticModel, container, this)); } } else { var block = node.Statement as BlockSyntax; foreach (var statement in block.Statements) { Block.Add(ItemFactory.Create(statement, semanticModel, container, this)); } } }
internal IfStatementOrElseClause(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } SyntaxKind kind = node.Kind(); if (kind == SyntaxKind.IfStatement) { _ifStatement = (IfStatementSyntax)node; _elseClause = null; } else if (kind == SyntaxKind.ElseClause) { _elseClause = (ElseClauseSyntax)node; _ifStatement = null; } else { throw new ArgumentException("Node must be either an if statement or an else clause.", nameof(node)); } }
ElseClauseSyntax GetNewIfWithElse(ElseClauseSyntax elseNode, StatementSyntax singleStatementInsideElse) { var newElse = elseNode .WithElseKeyword( elseNode.ElseKeyword .WithTrailingTrivia() ) .WithStatement( singleStatementInsideElse .WithLeadingTrivia(SyntaxFactory.Space) //.WithTrailingTrivia(trailingTriviaList) ); if (singleStatementInsideElse is ReturnStatementSyntax returnStatement) { if (returnStatement.Expression == null || returnStatement.Expression is LiteralExpressionSyntax || returnStatement.Expression.Span.Length <= MAX_RETURN_STATEMENT_LENGTH) { return(newElse); } } if (singleStatementInsideElse is IfStatementSyntax == false) { if ( singleStatementInsideElse.WithoutTrivia().DescendantTrivia().Any(t => t.IsKind(SyntaxKind.EndOfLineTrivia)) || singleStatementInsideElse.Span.Length + 5 > MAX_IF_LINE_LENGTH ) { return(elseNode.WithStatement(singleStatementInsideElse)); } } return(newElse); }
private static bool CheckTrivia(ElseClauseSyntax elseClause, IfStatementSyntax ifStatement) { TextSpan elseSpan = elseClause.Span; TextSpan ifSpan = ifStatement.Span; TextSpan span = TextSpan.FromBounds(elseSpan.Start, ifSpan.Start); TextSpan span2 = TextSpan.FromBounds(ifSpan.End, elseSpan.End); foreach (SyntaxTrivia trivia in elseClause.DescendantTrivia()) { TextSpan triviaSpan = trivia.Span; if (span.Contains(triviaSpan) || span2.Contains(triviaSpan)) { if (!trivia.IsWhitespaceOrEndOfLineTrivia()) { return(false); } } } return(true); }
internal static void AnalyzeIfStatement(SyntaxNodeAnalysisContext context) { var ifStatement = (IfStatementSyntax)context.Node; if (ifStatement.Condition?.WalkDownParentheses().IsMissing != false) return; StatementSyntax statement = ifStatement.Statement; if (statement == null) return; var block = statement as BlockSyntax; if (block?.Statements.Any() == false && block.OpenBraceToken.TrailingTrivia.IsEmptyOrWhitespace() && block.CloseBraceToken.LeadingTrivia.IsEmptyOrWhitespace()) { if (IsFixableIfElse(ifStatement)) context.ReportDiagnostic(DiagnosticDescriptors.SimplifyCodeBranching, ifStatement); } else { ElseClauseSyntax elseClause = ifStatement.Else; if (elseClause != null) { if (IsFixableIfElseInsideWhile(ifStatement, elseClause)) context.ReportDiagnostic(DiagnosticDescriptors.SimplifyCodeBranching, ifStatement); } else if (IsFixableIfInsideWhileOrDo(ifStatement)) { context.ReportDiagnostic(DiagnosticDescriptors.SimplifyCodeBranching, ifStatement); } } }
public override void VisitElseClause(ElseClauseSyntax node) { this.Write(node.ElseKeyword.ToFullString()); this.Visit(node.Statement); }
private SyntaxNode GetNewElseNode(ElseClauseSyntax elseClause) { return elseClause.WithStatement(SyntaxFactory.Block(elseClause.Statement)); }
public override void VisitElseClause(ElseClauseSyntax node) { VisitPossibleEmbeddedStatement(node.Statement, _enclosing); }
public static ImmutableArray <IfRefactoring> Analyze( IfStatementSyntax ifStatement, IfAnalysisOptions options, SemanticModel semanticModel, CancellationToken cancellationToken = default(CancellationToken)) { if (!ifStatement.IsTopmostIf()) { return(Empty); } ExpressionSyntax condition = ifStatement.Condition?.WalkDownParentheses(); if (condition == null) { return(Empty); } ElseClauseSyntax elseClause = ifStatement.Else; if (elseClause != null) { if (!options.CheckSpanDirectives(ifStatement)) { return(Empty); } StatementSyntax statement1 = ifStatement.GetSingleStatementOrDefault(); if (statement1 == null) { return(Empty); } SyntaxKind kind1 = statement1.Kind(); if (kind1.Is( SyntaxKind.ExpressionStatement, SyntaxKind.ReturnStatement, SyntaxKind.YieldReturnStatement)) { StatementSyntax statement2 = elseClause.GetSingleStatementOrDefault(); if (statement2?.Kind() == kind1) { switch (kind1) { case SyntaxKind.ExpressionStatement: { return(Analyze( ifStatement, condition, (ExpressionStatementSyntax)statement1, (ExpressionStatementSyntax)statement2, options, semanticModel, cancellationToken)); } case SyntaxKind.ReturnStatement: { return(Analyze( ifStatement, condition, ((ReturnStatementSyntax)statement1).Expression?.WalkDownParentheses(), ((ReturnStatementSyntax)statement2).Expression?.WalkDownParentheses(), options, isYield: false, semanticModel: semanticModel, cancellationToken: cancellationToken)); } case SyntaxKind.YieldReturnStatement: { return(Analyze( ifStatement, condition, ((YieldStatementSyntax)statement1).Expression?.WalkDownParentheses(), ((YieldStatementSyntax)statement2).Expression?.WalkDownParentheses(), options, isYield: true, semanticModel: semanticModel, cancellationToken: cancellationToken)); } } } } } else if (ifStatement.NextStatementOrDefault() is ReturnStatementSyntax returnStatement) { return(Analyze(ifStatement, returnStatement, options, semanticModel, cancellationToken)); } return(Empty); }
public static ImmutableArray <IfRefactoring> Analyze( IfStatementSyntax ifStatement, IfAnalysisOptions options, SemanticModel semanticModel, CancellationToken cancellationToken = default(CancellationToken)) { if (ifStatement.IsTopmostIf()) { ExpressionSyntax condition = ifStatement.Condition; if (condition != null) { ElseClauseSyntax elseClause = ifStatement.Else; if (elseClause != null) { if (options.CheckSpanDirectives(ifStatement)) { StatementSyntax statement1 = ifStatement.GetSingleStatementOrDefault(); if (statement1 != null) { SyntaxKind kind1 = statement1.Kind(); if (kind1 == SyntaxKind.ExpressionStatement || kind1 == SyntaxKind.ReturnStatement || kind1 == SyntaxKind.YieldReturnStatement) { StatementSyntax statement2 = elseClause.GetSingleStatementOrDefault(); if (statement2?.IsKind(kind1) == true) { switch (kind1) { case SyntaxKind.ExpressionStatement: { return(Analyze(ifStatement, condition, (ExpressionStatementSyntax)statement1, (ExpressionStatementSyntax)statement2, semanticModel, cancellationToken, options)); } case SyntaxKind.ReturnStatement: { return(Analyze(ifStatement, condition, ((ReturnStatementSyntax)statement1).Expression, ((ReturnStatementSyntax)statement2).Expression, semanticModel, cancellationToken, options, isYield: false)); } case SyntaxKind.YieldReturnStatement: { return(Analyze(ifStatement, condition, ((YieldStatementSyntax)statement1).Expression, ((YieldStatementSyntax)statement2).Expression, semanticModel, cancellationToken, options, isYield: true)); } } } } } } } else { StatementSyntax nextStatement = ifStatement.NextStatement(); if (nextStatement?.IsKind(SyntaxKind.ReturnStatement) == true) { return(Analyze(ifStatement, (ReturnStatementSyntax)nextStatement, options, semanticModel, cancellationToken)); } } } } return(ImmutableArray <IfRefactoring> .Empty); }
public override void VisitElseClause(ElseClauseSyntax node) { VisitPossibleEmbeddedStatement(node.Statement, _enclosing); }
public static void ComputeRefactoring(RefactoringContext context, IfStatementSyntax ifStatement) { if (IfElseChain.IsTopmostIf(ifStatement)) { ElseClauseSyntax elseClause = ifStatement.Else; if (elseClause != null) { StatementSyntax statement1 = ReplaceIfWithStatementRefactoring.GetStatement(ifStatement); if (statement1?.IsKind(SyntaxKind.ExpressionStatement) == true) { StatementSyntax statement2 = ReplaceIfWithStatementRefactoring.GetStatement(elseClause); if (statement2?.IsKind(SyntaxKind.ExpressionStatement) == true) { var expressionStatement1 = (ExpressionStatementSyntax)statement1; var expressionStatement2 = (ExpressionStatementSyntax)statement2; ExpressionSyntax expression1 = expressionStatement1.Expression; if (expression1?.IsKind(SyntaxKind.SimpleAssignmentExpression) == true) { ExpressionSyntax expression2 = expressionStatement2.Expression; if (expression2?.IsKind(SyntaxKind.SimpleAssignmentExpression) == true) { var assignment1 = (AssignmentExpressionSyntax)expression1; var assignment2 = (AssignmentExpressionSyntax)expression2; ExpressionSyntax left1 = assignment1.Left; ExpressionSyntax right1 = assignment1.Right; if (left1?.IsMissing == false && right1?.IsMissing == false) { ExpressionSyntax left2 = assignment2.Left; ExpressionSyntax right2 = assignment2.Right; if (left2?.IsMissing == false && right2?.IsMissing == false && left1.IsEquivalentTo(left2, topLevel: false)) { context.RegisterRefactoring( "Replace if-else with assignment", cancellationToken => { return(RefactorAsync( context.Document, ifStatement, left1, right1, right2, cancellationToken)); }); } } } } } } } } }
public override void VisitElseClause(ElseClauseSyntax node) { base.VisitElseClause(node); Count++; }
/// <summary> /// /// </summary> /// <param name="node"></param> public override sealed void VisitElseClause(ElseClauseSyntax node) { this.OnNodeVisited(node, this.type.IsInstanceOfType(node)); base.VisitElseClause(node); }
private bool AnalyzeElseClause(ElseClauseSyntax elseClause) => !elseClause.Statement.IsKind(SyntaxKind.Block) && !elseClause.Statement.IsKind(SyntaxKind.IfStatement);
public void VisitElseClause(ElseClauseSyntax node) { if (node == null) throw new ArgumentNullException("node"); _writer.WriteKeyword(PrinterKeyword.Else); if ( _writer.Configuration.Other.Other.SpecialElseIfTreatment && node.Statement is IfStatementSyntax ) { _writer.WriteSpace(); node.Statement.Accept(this); } else { VisitBlockStatement(node.Statement); } }
public static bool NeedsBraces(ElseClauseSyntax elseClause) { if (elseClause == null) { throw new ArgumentNullException("elseClause"); } return elseClause.Statement != null && !elseClause.Statement.IsKind(SyntaxKind.Block) && !elseClause.Statement.IsKind(SyntaxKind.IfStatement); }
private Decisions TraverseElseClauses(ElseClauseSyntax ecs, ref int exitPoints, bool nested = false) { Decisions retDecision = new Decisions(); ElseStatement elseStm = new ElseStatement(); if (ecs.HasLeadingTrivia) { SetOuterComments(elseStm, ecs.GetLeadingTrivia().ToFullString()); } if (ecs.HasTrailingTrivia) { SetInnerComments(elseStm, ecs.GetTrailingTrivia().ToFullString()); } elseStm.IsNested = nested; var binaryExpressions = from aBinaryExpression in ecs.ChildNodes().OfType<BinaryExpressionSyntax>() select aBinaryExpression; foreach (BinaryExpressionSyntax bes in binaryExpressions) { Method tempMethod = TraverseBinaryExpression(bes); elseStm.AccessedVars.AddRange(tempMethod.AccessedVariables); elseStm.InvokedMethods.AddRange(tempMethod.InvokedMethods); } var catches = from aCatch in ecs.ChildNodes().OfType<CatchClauseSyntax>() select aCatch; foreach (CatchClauseSyntax ccs in catches) { Decisions tempCatch = TraverseCatchClauses(ccs, ref exitPoints, true); elseStm.Nested.AddRange(tempCatch.Catches); } var elses = from aElse in ecs.ChildNodes().OfType<ElseClauseSyntax>() select aElse; foreach (ElseClauseSyntax ecs2 in elses) { Decisions tempElse = TraverseElseClauses(ecs2, ref exitPoints, true); elseStm.Nested.AddRange(tempElse.ElseStatements); } #region nested stuff var statements = from aStatement in ecs.ChildNodes().OfType<StatementSyntax>() select aStatement; foreach (StatementSyntax ss in statements) { if (ss is DoStatementSyntax) { Decisions dwl = TraverseDoStatements(ss as DoStatementSyntax, ref exitPoints, true); elseStm.Nested.AddRange(dwl.DoWhileLoops); } else if (ss is ExpressionStatementSyntax) { Method tempMethod = TraverseExpressionStatementSyntax(ss as ExpressionStatementSyntax); elseStm.AccessedVars.AddRange(tempMethod.AccessedVariables); elseStm.InvokedMethods.AddRange(tempMethod.InvokedMethods); } else if (ss is ForEachStatementSyntax) { Decisions fes = TraverseForEachStatements(ss as ForEachStatementSyntax, ref exitPoints, true); elseStm.Nested.AddRange(fes.ForEachStatements); } else if (ss is ForStatementSyntax) { Decisions fs = TraverseForStatements(ss as ForStatementSyntax, ref exitPoints, true); elseStm.Nested.AddRange(fs.ForStatements); } else if (ss is IfStatementSyntax) { Decisions decision = TraverseIfStatements(ss as IfStatementSyntax, ref exitPoints, true); elseStm.Nested.AddRange(decision.IfStatements); } else if (ss is LocalDeclarationStatementSyntax) { Model.Type tempType = new Model.Type(); LocalDeclarationStatementSyntax ldss = ss as LocalDeclarationStatementSyntax; if (ldss.Declaration != null) { VariableDeclarationSyntax vds = ldss.Declaration; tempType.Name = vds.Type.ToString(); tempType.IsKnownType = true; tempType.IsNotUserDefined = true; } Method tempMethod = TransverseAccessVars(ss as LocalDeclarationStatementSyntax); //NOT SURE if this will work but here goes tempMethod.AccessedVariables[0].Type = tempType; elseStm.AccessedVars.AddRange(tempMethod.AccessedVariables); elseStm.InvokedMethods.AddRange(tempMethod.InvokedMethods); } else if (ss is ReturnStatementSyntax) { exitPoints++; } else if (ss is SwitchStatementSyntax) { Decisions switchStm = TraverseSwitchStatements(ss as SwitchStatementSyntax, ref exitPoints, true); elseStm.Nested.AddRange(switchStm.SwitchStatements); } else if (ss is WhileStatementSyntax) { Decisions wl = TraverseWhileLoops(ss as WhileStatementSyntax, ref exitPoints, true); elseStm.Nested.AddRange(wl.WhileLoops); } } #endregion retDecision.ElseStatements.Add(elseStm); return retDecision; }
public static void Analyze(SyntaxNodeAnalysisContext context, IfStatementSyntax ifStatement) { SyntaxNode parent = ifStatement.Parent; if (parent?.IsKind(SyntaxKind.Block) == true) { ReturnStatementSyntax returnStatement = GetReturnStatement(ifStatement.Statement); LiteralExpressionSyntax booleanLiteral = GetBooleanLiteral(returnStatement); if (booleanLiteral != null) { ReturnStatementSyntax returnStatement2 = null; LiteralExpressionSyntax booleanLiteral2 = null; TextSpan span = ifStatement.Span; ElseClauseSyntax @else = ifStatement.Else; if (@else != null) { returnStatement2 = GetReturnStatement(@else.Statement); booleanLiteral2 = GetBooleanLiteral(returnStatement2); } else { var block = (BlockSyntax)parent; SyntaxList <StatementSyntax> statements = block.Statements; int index = statements.IndexOf(ifStatement); if (index < statements.Count - 1 && (index == 0 || !IsIfStatementWithReturnStatement(statements[index - 1]))) { StatementSyntax nextStatement = statements[index + 1]; if (nextStatement.IsKind(SyntaxKind.ReturnStatement)) { returnStatement2 = (ReturnStatementSyntax)nextStatement; booleanLiteral2 = GetBooleanLiteral(returnStatement2); if (booleanLiteral2 != null) { span = TextSpan.FromBounds(ifStatement.SpanStart, returnStatement2.Span.End); } } } } if (booleanLiteral2 != null && IsOppositeBooleanLiteral(booleanLiteral, booleanLiteral2) && parent .DescendantTrivia(span) .All(f => f.IsWhitespaceOrEndOfLineTrivia())) { context.ReportDiagnostic( DiagnosticDescriptors.ReplaceIfStatementWithReturnStatement, Location.Create(context.Node.SyntaxTree, span)); context.ReportToken(FadeOutDescriptor, ifStatement.IfKeyword); context.ReportToken(FadeOutDescriptor, ifStatement.OpenParenToken); context.ReportToken(FadeOutDescriptor, ifStatement.CloseParenToken); context.ReportNode(FadeOutDescriptor, ifStatement.Statement); if (ifStatement.Else != null) { context.ReportNode(FadeOutDescriptor, @else); } else { context.ReportNode(FadeOutDescriptor, returnStatement2); } } } } }
public virtual void VisitElseClause(ElseClauseSyntax node) { DefaultVisit(node); }
private static async Task <Document> RefactorAsync( Document document, IfStatementSyntax ifStatement, CancellationToken cancellationToken) { ExpressionSyntax condition = ifStatement.Condition; ElseClauseSyntax elseClause = ifStatement.Else; if ((ifStatement.Statement as BlockSyntax)?.Statements.Any() == false) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); ExpressionSyntax newCondition = Inverter.LogicallyNegate(condition, semanticModel, cancellationToken); StatementSyntax statement = elseClause.Statement; if (statement is IfStatementSyntax nestedIf) { newCondition = LogicalAndExpression(newCondition.Parenthesize(), nestedIf.Condition.Parenthesize()); statement = nestedIf.Statement; } cancellationToken.ThrowIfCancellationRequested(); IfStatementSyntax newNode = ifStatement.Update( ifStatement.IfKeyword, ifStatement.OpenParenToken, newCondition, ifStatement.CloseParenToken, statement, default(ElseClauseSyntax)); newNode = newNode.WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(ifStatement, newNode, cancellationToken).ConfigureAwait(false)); } else if (elseClause != null) { WhileStatementSyntax whileStatement; if (ifStatement.Parent is BlockSyntax block) { whileStatement = (WhileStatementSyntax)block.Parent; } else { block = Block(); whileStatement = (WhileStatementSyntax)ifStatement.Parent; } cancellationToken.ThrowIfCancellationRequested(); BlockSyntax newBlock = (ifStatement.Statement is BlockSyntax ifBlock) ? block.WithStatements(ifBlock.Statements) : block.WithStatements(SingletonList(ifStatement.Statement)); SyntaxNode newNode = whileStatement.Update( whileStatement.WhileKeyword, whileStatement.OpenParenToken, ifStatement.Condition, whileStatement.CloseParenToken, newBlock); newNode = newNode.WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(whileStatement, newNode, cancellationToken).ConfigureAwait(false)); } else { var block = (BlockSyntax)ifStatement.Parent; SyntaxList <StatementSyntax> statements = block.Statements; BlockSyntax newBlock = block.WithStatements(statements.Remove(ifStatement)); SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); ExpressionSyntax newCondition = Inverter.LogicallyNegate(condition, semanticModel, cancellationToken); SyntaxNode newNode = block.Parent; switch (block.Parent) { case WhileStatementSyntax whileStatement: { cancellationToken.ThrowIfCancellationRequested(); if (statements.IsFirst(ifStatement)) { newNode = whileStatement.Update( whileStatement.WhileKeyword, whileStatement.OpenParenToken, newCondition, whileStatement.CloseParenToken, newBlock); } else { newNode = DoStatement( Token(whileStatement.WhileKeyword.LeadingTrivia, SyntaxKind.DoKeyword, whileStatement.CloseParenToken.TrailingTrivia), newBlock.WithoutTrailingTrivia(), Token(SyntaxKind.WhileKeyword), OpenParenToken(), newCondition, CloseParenToken(), SemicolonToken().WithTrailingTrivia(newBlock.GetTrailingTrivia())); } break; } case DoStatementSyntax doStatement: { cancellationToken.ThrowIfCancellationRequested(); if (statements.IsLast(ifStatement)) { newNode = doStatement.Update( doStatement.DoKeyword, newBlock, doStatement.WhileKeyword, doStatement.OpenParenToken, newCondition, doStatement.CloseParenToken, doStatement.SemicolonToken); } else { newNode = WhileStatement( Token(doStatement.DoKeyword.LeadingTrivia, SyntaxKind.WhileKeyword, SyntaxTriviaList.Empty), OpenParenToken(), newCondition, Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, doStatement.DoKeyword.TrailingTrivia), newBlock.WithTrailingTrivia(doStatement.GetTrailingTrivia())); } break; } default: { Debug.Fail(block.Parent.Kind().ToString()); break; } } newNode = newNode.WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(block.Parent, newNode, cancellationToken).ConfigureAwait(false)); } }
/// <summary> /// /// </summary> /// <param name="node"></param> public override sealed void VisitElseClause(ElseClauseSyntax node) { this.OnNodeVisited(node); if (!this.traverseRootOnly) base.VisitElseClause(node); }
public ElseClauseTranslation(ElseClauseSyntax syntax, SyntaxTranslation parent) : base(syntax, parent) { Statement = syntax.Statement.Get<StatementTranslation>(this); }
private static bool IsFixableIfElseWithEmptyIf(IfStatementSyntax ifStatement, ElseClauseSyntax elseClause) { if (ifStatement.SpanContainsDirectives()) { return(false); } StatementSyntax whenFalse = elseClause.Statement; if (whenFalse == null) { return(false); } SyntaxKind kind = whenFalse.Kind(); if (kind == SyntaxKind.IfStatement) { var nestedIf = (IfStatementSyntax)whenFalse; if (nestedIf.Else != null) { return(false); } if (nestedIf.Condition?.WalkDownParentheses().IsMissing != false) { return(false); } StatementSyntax statement = nestedIf.Statement; if (statement == null) { return(false); } if ((statement as BlockSyntax)?.Statements.Any() == false) { return(false); } } else if (kind == SyntaxKind.Block) { if (!((BlockSyntax)whenFalse).Statements.Any()) { return(false); } } return(true); }
public override void VisitElseClause(ElseClauseSyntax node) { IncreaseComplexityByOne(node.ElseKeyword); base.VisitElseClause(node); }
private static ImmutableArray <IfRefactoring> Analyze( LocalDeclarationStatementSyntax localDeclarationStatement, IfStatementSyntax ifStatement, IfAnalysisOptions options) { VariableDeclaratorSyntax declarator = localDeclarationStatement .Declaration? .Variables .SingleOrDefault(shouldthrow: false); if (declarator == null) { return(Empty); } ElseClauseSyntax elseClause = ifStatement.Else; if (elseClause?.Statement?.IsKind(SyntaxKind.IfStatement) != false) { return(Empty); } SimpleAssignmentStatementInfo assignment1 = SyntaxInfo.SimpleAssignmentStatementInfo(ifStatement.GetSingleStatementOrDefault()); if (!assignment1.Success) { return(Empty); } SimpleAssignmentStatementInfo assignment2 = SyntaxInfo.SimpleAssignmentStatementInfo(elseClause.GetSingleStatementOrDefault()); if (!assignment2.Success) { return(Empty); } if (!assignment1.Left.IsKind(SyntaxKind.IdentifierName)) { return(Empty); } if (!assignment2.Left.IsKind(SyntaxKind.IdentifierName)) { return(Empty); } string identifier1 = ((IdentifierNameSyntax)assignment1.Left).Identifier.ValueText; string identifier2 = ((IdentifierNameSyntax)assignment2.Left).Identifier.ValueText; if (!string.Equals(identifier1, identifier2, StringComparison.Ordinal)) { return(Empty); } if (!string.Equals(identifier1, declarator.Identifier.ValueText, StringComparison.Ordinal)) { return(Empty); } if (!options.CheckSpanDirectives(ifStatement.Parent, TextSpan.FromBounds(localDeclarationStatement.SpanStart, ifStatement.Span.End))) { return(Empty); } return(new LocalDeclarationAndIfElseAssignmentWithConditionalExpression(localDeclarationStatement, ifStatement, assignment1.Right, assignment2.Right).ToImmutableArray()); }
private static SyntaxToken GetFirstExcludedToken(StatementSyntax statement) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return(((BlockSyntax)statement).CloseBraceToken); case SyntaxKind.BreakStatement: return(((BreakStatementSyntax)statement).SemicolonToken); case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return(((CheckedStatementSyntax)statement).Block.CloseBraceToken); case SyntaxKind.ContinueStatement: return(((ContinueStatementSyntax)statement).SemicolonToken); case SyntaxKind.LocalDeclarationStatement: return(((LocalDeclarationStatementSyntax)statement).SemicolonToken); case SyntaxKind.DoStatement: return(((DoStatementSyntax)statement).SemicolonToken); case SyntaxKind.EmptyStatement: return(((EmptyStatementSyntax)statement).SemicolonToken); case SyntaxKind.ExpressionStatement: return(((ExpressionStatementSyntax)statement).SemicolonToken); case SyntaxKind.FixedStatement: return(GetFirstExcludedToken(((FixedStatementSyntax)statement).Statement)); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return(GetFirstExcludedToken(((CommonForEachStatementSyntax)statement).Statement)); case SyntaxKind.ForStatement: return(GetFirstExcludedToken(((ForStatementSyntax)statement).Statement)); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return(((GotoStatementSyntax)statement).SemicolonToken); case SyntaxKind.IfStatement: IfStatementSyntax ifStmt = (IfStatementSyntax)statement; ElseClauseSyntax elseOpt = ifStmt.Else; return(GetFirstExcludedToken(elseOpt == null ? ifStmt.Statement : elseOpt.Statement)); case SyntaxKind.LabeledStatement: return(GetFirstExcludedToken(((LabeledStatementSyntax)statement).Statement)); case SyntaxKind.LockStatement: return(GetFirstExcludedToken(((LockStatementSyntax)statement).Statement)); case SyntaxKind.ReturnStatement: return(((ReturnStatementSyntax)statement).SemicolonToken); case SyntaxKind.SwitchStatement: return(((SwitchStatementSyntax)statement).CloseBraceToken); case SyntaxKind.ThrowStatement: return(((ThrowStatementSyntax)statement).SemicolonToken); case SyntaxKind.TryStatement: TryStatementSyntax tryStmt = (TryStatementSyntax)statement; FinallyClauseSyntax finallyClause = tryStmt.Finally; if (finallyClause != null) { return(finallyClause.Block.CloseBraceToken); } CatchClauseSyntax lastCatch = tryStmt.Catches.LastOrDefault(); if (lastCatch != null) { return(lastCatch.Block.CloseBraceToken); } return(tryStmt.Block.CloseBraceToken); case SyntaxKind.UnsafeStatement: return(((UnsafeStatementSyntax)statement).Block.CloseBraceToken); case SyntaxKind.UsingStatement: return(GetFirstExcludedToken(((UsingStatementSyntax)statement).Statement)); case SyntaxKind.WhileStatement: return(GetFirstExcludedToken(((WhileStatementSyntax)statement).Statement)); case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return(((YieldStatementSyntax)statement).SemicolonToken); case SyntaxKind.LocalFunctionStatement: LocalFunctionStatementSyntax localFunctionStmt = (LocalFunctionStatementSyntax)statement; if (localFunctionStmt.Body != null) { return(GetFirstExcludedToken(localFunctionStmt.Body)); } if (localFunctionStmt.SemicolonToken != default(SyntaxToken)) { return(localFunctionStmt.SemicolonToken); } return(localFunctionStmt.ParameterList.GetLastToken()); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } }
private IfStatementSyntax ParseIfStatement(List<AttributeSyntax> attributes) { var @if = Match(SyntaxKind.IfKeyword); var openParen = Match(SyntaxKind.OpenParenToken); var condition = ParseExpression(); var closeParen = Match(SyntaxKind.CloseParenToken); var statement = ParseEmbeddedStatement(); ElseClauseSyntax @else = null; if (Current.Kind == SyntaxKind.ElseKeyword) { var elseToken = Match(SyntaxKind.ElseKeyword); var elseStatement = ParseEmbeddedStatement(); @else = new ElseClauseSyntax(elseToken, elseStatement); } return new IfStatementSyntax(attributes, @if, openParen, condition, closeParen, statement, @else); }
private bool AnalyzeElseClause(ElseClauseSyntax elseClause) => !elseClause.Statement.IsKind(SyntaxKind.Block) && !elseClause.Statement.IsKind(SyntaxKind.IfStatement);
public static string ElseClause(ElseClauseSyntax clause) { var output = clause.ElseKeyword.Text + " "; output += SyntaxNode(clause.Statement); return output; }