private VB.Syntax.ForStepClauseSyntax CreateForStepClause(CS.Syntax.ForStatementSyntax node) { ExpressionSyntax incrementor = node.Incrementors[0]; if (!incrementor.IsKind(CS.SyntaxKind.PreIncrementExpression) && !incrementor.IsKind(CS.SyntaxKind.PostIncrementExpression)) { if (incrementor.IsKind(CS.SyntaxKind.PreDecrementExpression) || incrementor.IsKind(CS.SyntaxKind.PostDecrementExpression)) { return(VB.SyntaxFactory.ForStepClause( VB.SyntaxFactory.UnaryMinusExpression(CreateOneExpression()))); } if (incrementor.IsKind(CS.SyntaxKind.AddAssignmentExpression)) { return(VB.SyntaxFactory.ForStepClause(nodeVisitor.VisitExpression(((CS.Syntax.AssignmentExpressionSyntax)incrementor).Right))); } if (incrementor.IsKind(CS.SyntaxKind.SubtractAssignmentExpression)) { return(VB.SyntaxFactory.ForStepClause(VB.SyntaxFactory.UnaryMinusExpression( nodeVisitor.VisitExpression(((CS.Syntax.AssignmentExpressionSyntax)incrementor).Right)))); } } return(null); }
static bool HasAcceptableIncrementors(ForStatementSyntax @for) { if (@for.Incrementors.Count != 1) return false; var unary = @for.Incrementors[0] as PostfixUnaryExpressionSyntax; if (unary == null) return false; return unary.IsKind(SyntaxKind.PostIncrementExpression) || unary.IsKind(SyntaxKind.PostDecrementExpression); }
public override SyntaxList <StatementSyntax> VisitForStatement(CSS.ForStatementSyntax node) { StatementSyntax block; if (!ConvertForToSimpleForNext(node, out block)) { var stmts = ConvertBlock(node.Statement) .AddRange(node.Incrementors.Select(ConvertSingleExpression)); var condition = node.Condition == null?CommonConversions.Literal(true) : (ExpressionSyntax)node.Condition.Accept(_nodesVisitor); block = SyntaxFactory.WhileBlock( SyntaxFactory.WhileStatement(condition), stmts ); var declarations = new List <StatementSyntax>(); if (node.Declaration != null) { var syntaxTokenList = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.DimKeyword)); declarations.Add(SyntaxFactory.LocalDeclarationStatement(syntaxTokenList, _commonConversions.RemodelVariableDeclaration(node.Declaration))); } return(SyntaxFactory.List(declarations.Concat(node.Initializers.Select(ConvertSingleExpression))).Add(block)); } return(SyntaxFactory.SingletonList(block)); }
private BoundForStatement BindForParts(ForStatementSyntax node, Binder originalBinder, DiagnosticBag diagnostics) { BoundStatement initializer; if (node.Declaration != null) { Debug.Assert(node.Initializers.Count == 0); if (node.Declaration.IsDeconstructionDeclaration) { initializer = originalBinder.BindDeconstructionDeclaration(node.Declaration, node.Declaration, diagnostics); } else { ImmutableArray<BoundLocalDeclaration> unused; initializer = originalBinder.BindForOrUsingOrFixedDeclarations(node.Declaration, LocalDeclarationKind.ForInitializerVariable, diagnostics, out unused); } } else { initializer = originalBinder.BindStatementExpressionList(node.Initializers, diagnostics); } var condition = (node.Condition != null) ? originalBinder.BindBooleanExpression(node.Condition, diagnostics) : null; var increment = originalBinder.BindStatementExpressionList(node.Incrementors, diagnostics); var body = originalBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics); Debug.Assert(this.Locals == this.GetDeclaredLocalsForScope(node)); return new BoundForStatement(node, this.Locals, initializer, condition, increment, body, this.BreakLabel, this.ContinueLabel); }
static bool AreDeclarationConditionAndIncrementorUsingTheSameVariable(ForStatementSyntax @for) { SyntaxToken reference; if (@for.Declaration != null) { reference = @for.Declaration.Variables[0].Identifier; } else { var initializer = @for.Initializers[0] as AssignmentExpressionSyntax; if (initializer == null) return false; var name = initializer.Left as IdentifierNameSyntax; if (name == null) return false; reference = name.Identifier; } var condition = @for.Condition as BinaryExpressionSyntax; var incrementor = @for.Incrementors[0] as PostfixUnaryExpressionSyntax; if (!(condition.Left is IdentifierNameSyntax)) return false; if (!(incrementor.Operand is IdentifierNameSyntax)) return false; var conditionVariableIdentifier = (condition.Left as IdentifierNameSyntax).Identifier; var incrementorVariableIdentifier = (incrementor.Operand as IdentifierNameSyntax).Identifier; return reference.Text == conditionVariableIdentifier.Text && reference.Text == incrementorVariableIdentifier.Text; }
public static ForStatementSyntax AddBraces(ForStatementSyntax forStatement) { Debug.Assert(forStatement != null && NeedsBraces(forStatement)); return forStatement .WithStatement(SyntaxFactory.Block(forStatement.Statement)) .WithAdditionalAnnotations(Formatter.Annotation); }
public override void VisitForStatement(ForStatementSyntax node) { if (!(node.Statement is BlockSyntax)) { CreateAuditVariable(node.Statement); } base.VisitForStatement(node); }
public override SyntaxList <VB.Syntax.StatementSyntax> VisitForStatement(CS.Syntax.ForStatementSyntax node) { // VB doesn't have a For statement that directly maps to C#'s. However, some C# for // statements will map to a VB for statement. Check for those common cases and // translate those. return(IsSimpleForStatement(node) ? VisitSimpleForStatement(node) : VisitComplexForStatement(node)); }
public override void VisitForStatement(ForStatementSyntax node) { if (node.Condition != null) { _builder.Add(node); } base.VisitForStatement(node); }
internal ForInitializerBlock(ForStatementSyntax forNode, Block successor) : base(successor) { if (forNode == null) { throw new ArgumentNullException(nameof(forNode)); } ForNode = forNode; }
static bool HasConditionCompatibleWithTheIncrementor(ForStatementSyntax @for) { var condition = @for.Condition as BinaryExpressionSyntax; var postIncrement = IsPostIncrement(@for.Incrementors[0]); return condition != null && ( (postIncrement && condition.OperatorToken.IsKind(SyntaxKind.LessThanToken)) || (!postIncrement && condition.OperatorToken.IsKind(SyntaxKind.GreaterThanEqualsToken)) ); }
public static string ForStatement(ForStatementSyntax statement) { var output = "for "; output += SyntaxNode(statement.Declaration) + "; " + SyntaxNode(statement.Condition) + "; " + //TODO: these semicolons should be handled in their syntaxParsers SyntaxNode(statement.Incrementors.First()).TrimEnd(); //TODO: handle multiple incrementors output += " " + SyntaxNode(statement.Statement); return output; }
public override void VisitForStatement(ForStatementSyntax node) { if (node.Declaration != null) { AddVariableExpressions(node.Declaration.Variables, _expressions); } node.Initializers.Do(i => AddExpressionTerms(i, _expressions)); AddExpressionTerms(node.Condition, _expressions); node.Incrementors.Do(i => AddExpressionTerms(i, _expressions)); }
private VB.Syntax.ForStatementSyntax CreateForStatement(CS.Syntax.ForStatementSyntax node) { string variableName = node.Declaration.Variables[0].Identifier.ValueText; VB.Syntax.ForStepClauseSyntax stepClause = CreateForStepClause(node); VB.Syntax.ExpressionSyntax toValue = CreateForToValue(node); return(VB.SyntaxFactory.ForStatement( controlVariable: VB.SyntaxFactory.IdentifierName(variableName), fromValue: nodeVisitor.VisitExpression(node.Declaration.Variables[0].Initializer.Value), toValue: toValue, stepClause: stepClause)); }
private SyntaxList <VB.Syntax.StatementSyntax> VisitSimpleForStatement(CS.Syntax.ForStatementSyntax node) { VB.Syntax.ForStatementSyntax forStatement = CreateForStatement(node); IEnumerable <VB.Syntax.StatementSyntax> statements = VisitStatementEnumerable(node.Statement); VB.Syntax.ForBlockSyntax forBlock = VB.SyntaxFactory.ForBlock( forStatement, List(statements), VB.SyntaxFactory.NextStatement()); return(List <VB.Syntax.StatementSyntax>(forBlock)); }
public override SyntaxNode VisitForStatement(ForStatementSyntax node) { node = (ForStatementSyntax)base.VisitForStatement(node); if (!node.Statement.IsKind(SyntaxKind.Block)) { this.addedAnnotations = true; node = node.WithStatement(SyntaxFactory.Block(node.Statement)); } return node; }
public override void VisitForStatement(ForStatementSyntax forStatement) { var initializers = string.Join(" ", forStatement.Initializers.Select(o => o.ToString())); var condition = forStatement.Condition?.ToString(); var interator = string.Join(" ", forStatement.Incrementors.Select(o => o.ToString())); var expression = $"for ({initializers}; {condition}; {interator})"; var token = CreateBlock(expression, SDNodeRole.ForLoop); _tokenList.Add(token); VisitChildren(token.Statements, forStatement.Statement); }
public override void VisitForStatement(ForStatementSyntax node) { var tokens = new List<SyntaxToken>(); if (node.Declaration != null) { tokens.AddRange(node.Declaration.Variables.Select(v => v.Identifier)); } tracker.AddIdentifiers(tokens); Visit(node.Statement); tracker.RemoveIdentifiers(tokens); }
public ForStatementTranslation(ForStatementSyntax syntax, SyntaxTranslation parent) : base(syntax, parent) { //KeyValuePair<int, string>? a = null; //var b = ((bool?)null)?.Equals(false) ?? true ? false ? true : false :true; //string str = "\{ ("\{( "(\{ "{}" })" )}") }"; Condition = syntax.Condition.Get<ExpressionTranslation>(this); Declaration = syntax.Declaration.Get<VariableDeclarationTranslation>(this); Incrementors = syntax.Incrementors.Get<ExpressionSyntax, ExpressionTranslation>(this); Initializers = syntax.Initializers.Get<ExpressionSyntax, ExpressionTranslation>(this); Statement = syntax.Statement.Get<StatementTranslation>(this); }
private BoundForStatement BindForParts(ForStatementSyntax node, Binder originalBinder, DiagnosticBag diagnostics) { BoundStatement initializer; // Declaration and Initializers are mutually exclusive. if (_syntax.Declaration != null) { ImmutableArray<BoundLocalDeclaration> unused; initializer = originalBinder.BindForOrUsingOrFixedDeclarations(node.Declaration, LocalDeclarationKind.RegularVariable, diagnostics, out unused); } else { initializer = originalBinder.BindStatementExpressionList(node.Initializers, diagnostics); } BoundExpression condition = null; var innerLocals = ImmutableArray<LocalSymbol>.Empty; ExpressionSyntax conditionSyntax = node.Condition; if (conditionSyntax != null) { originalBinder = originalBinder.GetBinder(conditionSyntax); condition = originalBinder.BindBooleanExpression(conditionSyntax, diagnostics); innerLocals = originalBinder.GetDeclaredLocalsForScope(conditionSyntax); } BoundStatement increment = null; SeparatedSyntaxList<ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var scopeDesignator = incrementors.First(); var incrementBinder = originalBinder.GetBinder(scopeDesignator); increment = incrementBinder.WrapWithVariablesIfAny(scopeDesignator, incrementBinder.BindStatementExpressionList(incrementors, diagnostics)); } var body = originalBinder.BindPossibleEmbeddedStatement(node.Statement, diagnostics); Debug.Assert(this.Locals == this.GetDeclaredLocalsForScope(node)); return new BoundForStatement(node, this.Locals, initializer, innerLocals, condition, increment, body, this.BreakLabel, this.ContinueLabel); }
public override SyntaxList <StatementSyntax> VisitForStatement(CSS.ForStatementSyntax node) { StatementSyntax block; if (!ConvertForToSimpleForNext(node, out block)) { var stmts = ConvertBlock(node.Statement) .AddRange(node.Incrementors.Select(ConvertSingleExpression)); var condition = node.Condition == null?Literal(true) : (ExpressionSyntax)node.Condition.Accept(nodesVisitor); block = SyntaxFactory.WhileBlock( SyntaxFactory.WhileStatement(condition), stmts ); return(SyntaxFactory.List(node.Initializers.Select(ConvertSingleExpression)).Add(block)); } return(SyntaxFactory.SingletonList(block)); }
private static async Task<Document> ConvertToDecrementingCounterForLoopAsync(Document document, ForStatementSyntax @for, CancellationToken cancellationToken) { var condition = (BinaryExpressionSyntax)@for.Condition; var newEndValue = @for.Declaration != null ? @for.Declaration.Variables[0].Initializer.Value : (@for.Initializers[0] as AssignmentExpressionSyntax).Right; var newStartValue = SyntaxFactory.BinaryExpression(SyntaxKind.SubtractExpression, condition.Right, One); var newDeclaration = ReplaceStartValue(@for.Declaration, newStartValue); var newInitializers = ReplaceStartValue(@for.Initializers, newStartValue); var newCondition = condition .WithOperatorToken(SyntaxFactory.Token(SyntaxKind.GreaterThanEqualsToken)) .WithRight(newEndValue); return await ReplaceForAsync(document, @for, newDeclaration, newInitializers, newCondition, cancellationToken); }
private SyntaxList <VB.Syntax.StatementSyntax> VisitComplexForStatement(CS.Syntax.ForStatementSyntax node) { // VB doesn't have a for loop. So convert: // for (declarations; condition; incrementors) body into: // // declarations // while (condition) { // body; // incrementors; // } VB.Syntax.WhileStatementSyntax begin; if (node.Condition == null) { begin = VB.SyntaxFactory.WhileStatement( condition: VB.SyntaxFactory.TrueLiteralExpression(VB.SyntaxFactory.Token(VB.SyntaxKind.TrueKeyword))); } else { begin = VB.SyntaxFactory.WhileStatement( condition: nodeVisitor.VisitExpression(node.Condition)); } SyntaxList <VB.Syntax.StatementSyntax> initialBlock = Visit(node.Statement); List <VB.Syntax.StatementSyntax> whileStatements = initialBlock.Concat( node.Incrementors.Select(nodeVisitor.VisitStatement)).ToList(); SyntaxList <VB.Syntax.StatementSyntax> whileBody = List <VB.Syntax.StatementSyntax>(whileStatements); VB.Syntax.WhileBlockSyntax whileBlock = VB.SyntaxFactory.WhileBlock( begin, whileBody); List <VB.Syntax.StatementSyntax> statements = new List <VB.Syntax.StatementSyntax>(); if (node.Declaration != null) { statements.Add(nodeVisitor.Visit <VB.Syntax.StatementSyntax>(node.Declaration)); } statements.Add(whileBlock); return(List <VB.Syntax.StatementSyntax>(statements)); }
public override void VisitForStatement(ForStatementSyntax node) { foreach (var invocation in node.DescendantNodes().OfType<InvocationExpressionSyntax>()) { var symbol = (IMethodSymbol)SemanticModel.GetSymbolInfo(invocation).Symbol; if (symbol!=null && symbol.IsTaskCreationMethod()) { Logs.TempLog.Info("{0}{1}--------------------------", Document.FilePath, node.Parent.ToLog()); break; } if (symbol != null && symbol.IsThreadStart()) { Logs.TempLog4.Info("{0}{1}--------------------------", Document.FilePath, node.Parent.ToLog()); break; } } base.VisitForStatement(node); }
private bool IsSimpleForDeclaration(CS.Syntax.ForStatementSyntax node) { #if false Declaration must be one of: var name = v1 primitive_type name = v1 #endif if (node.Declaration != null && node.Declaration.Variables.Count == 1 && node.Declaration.Variables[0].Initializer != null) { if (node.Declaration.Type.IsVar || node.Declaration.Type.IsKind(CS.SyntaxKind.PredefinedType)) { return(true); } } return(false); }
private VB.Syntax.ExpressionSyntax CreateForToValue(CS.Syntax.ForStatementSyntax node) { VB.Syntax.ExpressionSyntax expression = nodeVisitor.VisitExpression(((CS.Syntax.BinaryExpressionSyntax)node.Condition).Right); if (!node.Condition.IsKind(CS.SyntaxKind.LessThanOrEqualExpression) && !node.Condition.IsKind(CS.SyntaxKind.GreaterThanOrEqualExpression)) { if (node.Condition.IsKind(CS.SyntaxKind.LessThanExpression)) { return(VB.SyntaxFactory.SubtractExpression( expression, CreateOneExpression())); } if (node.Condition.IsKind(CS.SyntaxKind.GreaterThanExpression)) { return(VB.SyntaxFactory.AddExpression( expression, CreateOneExpression())); } } return(expression); }
private bool IsSimpleForIncrementor(CS.Syntax.ForStatementSyntax node, string variableName) { #if false name++; name--; ++name; --name; name += v3; name -= v3; #endif if (node.Incrementors.Count == 1) { ExpressionSyntax incrementor = node.Incrementors[0]; if (incrementor.IsKind(CS.SyntaxKind.PostIncrementExpression) || incrementor.IsKind(CS.SyntaxKind.PostDecrementExpression)) { return(((CS.Syntax.PostfixUnaryExpressionSyntax)incrementor).Operand is CS.Syntax.IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == variableName); } if (incrementor.IsKind(CS.SyntaxKind.PreIncrementExpression) || incrementor.IsKind(CS.SyntaxKind.PreDecrementExpression)) { return(((CS.Syntax.PrefixUnaryExpressionSyntax)incrementor).Operand is CS.Syntax.IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == variableName); } if (incrementor.IsKind(CS.SyntaxKind.AddAssignmentExpression) || incrementor.IsKind(CS.SyntaxKind.SubtractAssignmentExpression)) { AssignmentExpressionSyntax binaryExpression = (CS.Syntax.AssignmentExpressionSyntax)incrementor; return(binaryExpression.Left is CS.Syntax.IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == variableName); } } return(false); }
private bool IsSimpleForCondition(CS.Syntax.ForStatementSyntax node, string variableName) { #if false Condition must be one of: name <v2 name <= v2 name> v2 name >= v2 #endif if (node.Condition != null) { if (node.Condition.IsKind(CS.SyntaxKind.LessThanExpression) || node.Condition.IsKind(CS.SyntaxKind.LessThanOrEqualExpression) || node.Condition.IsKind(CS.SyntaxKind.GreaterThanExpression) || node.Condition.IsKind(CS.SyntaxKind.GreaterThanOrEqualExpression)) { BinaryExpressionSyntax binaryExpression = (CS.Syntax.BinaryExpressionSyntax)node.Condition; return(binaryExpression.Left is CS.Syntax.IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == variableName); } } return(false); }
private bool IsSimpleForStatement(CS.Syntax.ForStatementSyntax node) { // Has to look like one of the following: #if false for (Declaration; Condition; Incrementor) { Declaration must be one of: var name = v1 primitive_type name = v1 Condition must be one of: name <v2 name <= v2 name> v2 name >= v2 Incrementor must be one of: name++; } name--; name += v3; name -= v3; #endif if (node.Declaration == null || node.Declaration.Variables.Count != 1) { return(false); } string variableName = node.Declaration.Variables[0].Identifier.ValueText; return (IsSimpleForDeclaration(node) && IsSimpleForCondition(node, variableName) && IsSimpleForIncrementor(node, variableName)); }
public ForLoopBinder(Binder enclosing, ForStatementSyntax syntax) : base(enclosing) { Debug.Assert(syntax != null); _syntax = syntax; }
public override void VisitForStatement(ForStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); Binder binder = new ForLoopBinder(_enclosing, node); AddToMap(node, binder); var declaration = node.Declaration; if (declaration != null) { foreach (var variable in declaration.Variables) { Visit(variable, binder); } } else { foreach (var initializer in node.Initializers) { Visit(initializer, binder); } } ExpressionSyntax condition = node.Condition; if (condition != null) { binder = new ExpressionVariableBinder(condition, binder); AddToMap(condition, binder); Visit(condition, binder); } SeparatedSyntaxList<ExpressionSyntax> incrementors = node.Incrementors; if (incrementors.Count > 0) { var incrementorsBinder = new ExpressionListVariableBinder(incrementors, binder); AddToMap(incrementors.First(), incrementorsBinder); foreach (var incrementor in incrementors) { Visit(incrementor, incrementorsBinder); } } VisitPossibleEmbeddedStatement(node.Statement, binder); }
public override SyntaxNode VisitForStatement(ForStatementSyntax node) { _output.Write(node.ForKeyword, "for ("); if (node.Initializers != null) { this.MakeExpressionList(node.Initializers); } if (node.Declaration != null) { _output.TrivialWrite("var "); this.MakeLocalVariableList(node.Declaration); } _output.TrivialWrite("; "); this.VisitExpression(node.Condition); _output.TrivialWrite("; "); this.MakeExpressionList(node.Incrementors); _output.TrivialWriteLine(") {"); _output.IncreaseIndent(); this.Visit(node.Statement); this.AppendCompensateSemicolon(node.Statement); _output.DecreaseIndent(); _output.TrivialWrite('}'); return node; }
public override void VisitForStatement(ForStatementSyntax node) { Debug.Assert((object)_method == _enclosing.ContainingMemberOrLambda); var binder = new ForLoopBinder(_enclosing, node); AddToMap(node, binder); VisitPossibleEmbeddedStatement(node.Statement, binder); }
public BoundForStatement BindFor(ForStatementSyntax node, DiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindForParts(diagnostics, loopBinder); }
public override void VisitForStatement(ForStatementSyntax node) { Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda); var binder = new ForLoopBinder(_enclosing, node); AddToMap(node, binder); var declaration = node.Declaration; if (declaration != null) { foreach (var variable in declaration.Variables) { if (variable.Initializer != null) { Visit(variable.Initializer.Value, binder); } } } else { foreach (var initializer in node.Initializers) { Visit(initializer, binder); } } if (node.Condition != null) { Visit(node.Condition, binder); } foreach (var incrementor in node.Incrementors) { Visit(incrementor, binder); } VisitPossibleEmbeddedStatement(node.Statement, binder); }
bool ConvertForToSimpleForNext(CSS.ForStatementSyntax node, out StatementSyntax block) { // ForStatement -> ForNextStatement when for-loop is simple // only the following forms of the for-statement are allowed: // for (TypeReference name = start; name < oneAfterEnd; name += step) // for (name = start; name < oneAfterEnd; name += step) // for (TypeReference name = start; name <= end; name += step) // for (name = start; name <= end; name += step) // for (TypeReference name = start; name > oneAfterEnd; name -= step) // for (name = start; name > oneAfterEnd; name -= step) // for (TypeReference name = start; name >= end; name -= step) // for (name = start; name >= end; name -= step) block = null; // check if the form is valid and collect TypeReference, name, start, end and step bool hasVariable = node.Declaration != null && node.Declaration.Variables.Count == 1; if (!hasVariable && node.Initializers.Count != 1) { return(false); } if (node.Incrementors.Count != 1) { return(false); } var iterator = node.Incrementors.FirstOrDefault()?.Accept(_nodesVisitor) as AssignmentStatementSyntax; if (iterator == null || !iterator.IsKind(SyntaxKind.AddAssignmentStatement, SyntaxKind.SubtractAssignmentStatement)) { return(false); } var iteratorIdentifier = iterator.Left as IdentifierNameSyntax; if (iteratorIdentifier == null) { return(false); } var stepExpression = iterator.Right as LiteralExpressionSyntax; if (stepExpression == null || !(stepExpression.Token.Value is int)) { return(false); } int step = (int)stepExpression.Token.Value; if (SyntaxTokenExtensions.IsKind(iterator.OperatorToken, SyntaxKind.MinusEqualsToken)) { step = -step; } var condition = node.Condition as CSS.BinaryExpressionSyntax; if (condition == null || !(condition.Left is CSS.IdentifierNameSyntax)) { return(false); } if (((CSS.IdentifierNameSyntax)condition.Left).Identifier.IsEquivalentTo(iteratorIdentifier.Identifier)) { return(false); } ExpressionSyntax end; if (iterator.IsKind(SyntaxKind.SubtractAssignmentStatement)) { if (condition.IsKind(CS.SyntaxKind.GreaterThanOrEqualExpression)) { end = (ExpressionSyntax)condition.Right.Accept(_nodesVisitor); } else if (condition.IsKind(CS.SyntaxKind.GreaterThanExpression)) { end = SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, (ExpressionSyntax)condition.Right.Accept(_nodesVisitor), SyntaxFactory.Token(SyntaxKind.PlusToken), CommonConversions.Literal(1)); } else { return(false); } } else { if (condition.IsKind(CS.SyntaxKind.LessThanOrEqualExpression)) { end = (ExpressionSyntax)condition.Right.Accept(_nodesVisitor); } else if (condition.IsKind(CS.SyntaxKind.LessThanExpression)) { end = SyntaxFactory.BinaryExpression(SyntaxKind.SubtractExpression, (ExpressionSyntax)condition.Right.Accept(_nodesVisitor), SyntaxFactory.Token(SyntaxKind.MinusToken), CommonConversions.Literal(1)); } else { return(false); } } VisualBasicSyntaxNode variable; ExpressionSyntax start; if (hasVariable) { var v = node.Declaration.Variables[0]; start = (ExpressionSyntax)v.Initializer?.Value.Accept(_nodesVisitor); if (start == null) { return(false); } variable = SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(_commonConversions.ConvertIdentifier(v.Identifier))), node.Declaration.Type.IsVar ? null : SyntaxFactory.SimpleAsClause((TypeSyntax)node.Declaration.Type.Accept(_nodesVisitor)), null ); } else { var initializer = node.Initializers.FirstOrDefault() as CSS.AssignmentExpressionSyntax; if (initializer == null || !initializer.IsKind(CS.SyntaxKind.SimpleAssignmentExpression)) { return(false); } if (!(initializer.Left is CSS.IdentifierNameSyntax)) { return(false); } if (((CSS.IdentifierNameSyntax)initializer.Left).Identifier.IsEquivalentTo(iteratorIdentifier.Identifier)) { return(false); } variable = initializer.Left.Accept(_nodesVisitor); start = (ExpressionSyntax)initializer.Right.Accept(_nodesVisitor); } block = SyntaxFactory.ForBlock( SyntaxFactory.ForStatement(variable, start, end, step == 1 ? null : SyntaxFactory.ForStepClause(CommonConversions.Literal(step))), ConvertBlock(node.Statement), SyntaxFactory.NextStatement() ); return(true); }
private bool ConvertForToSimpleForNextWithoutStatements(CSS.ForStatementSyntax node, out ForBlockSyntax blockWithoutStatements) { // ForStatement -> ForNextStatement when for-loop is simple // only the following forms of the for-statement are allowed: // for (TypeReference name = start; name < oneAfterEnd; name += step) // for (name = start; name < oneAfterEnd; name += step) // for (TypeReference name = start; name <= end; name += step) // for (name = start; name <= end; name += step) // for (TypeReference name = start; name > oneAfterEnd; name -= step) // for (name = start; name > oneAfterEnd; name -= step) // for (TypeReference name = start; name >= end; name -= step) // for (name = start; name >= end; name -= step) blockWithoutStatements = null; // check if the form is valid and collect TypeReference, name, start, end and step bool hasVariable = node.Declaration != null && node.Declaration.Variables.Count == 1; if (!hasVariable && node.Initializers.Count != 1) { return(false); } if (node.Incrementors.Count != 1) { return(false); } var iterator = node.Incrementors.FirstOrDefault()?.Accept(_nodesVisitor) as AssignmentStatementSyntax; if (iterator == null || !iterator.IsKind(SyntaxKind.AddAssignmentStatement, SyntaxKind.SubtractAssignmentStatement)) { return(false); } var iteratorIdentifier = iterator.Left as IdentifierNameSyntax; if (iteratorIdentifier == null) { return(false); } var stepExpression = iterator.Right as LiteralExpressionSyntax; if (stepExpression == null || !(stepExpression.Token.Value is int)) { return(false); } int step = (int)stepExpression.Token.Value; if (SyntaxTokenExtensions.IsKind(iterator.OperatorToken, SyntaxKind.MinusEqualsToken)) { step = -step; } var condition = node.Condition as CSS.BinaryExpressionSyntax; if (condition == null || !(condition.Left is CSS.IdentifierNameSyntax)) { return(false); } if (((CSS.IdentifierNameSyntax)condition.Left).Identifier.IsEquivalentTo(iteratorIdentifier.Identifier)) { return(false); } ExpressionSyntax end; var rightExpression = (ExpressionSyntax)condition.Right.Accept(_nodesVisitor); var rightVal = (rightExpression is LiteralExpressionSyntax && _semanticModel.GetConstantValue(condition.Right) is { Value : int r }) ? r : default(int?);
/// <summary> /// Handles the given for statement. /// </summary> /// <param name="stmt">Statement</param> /// <param name="successor">Successor</param> private void HandleForStatement(ForStatementSyntax stmt, ControlFlowGraphNode successor) { this.SyntaxNodes.Add(stmt.Condition); this.IsLoopHeadNode = true; if (successor != null) { this.ISuccessors.Add(successor); successor.IPredecessors.Add(this); this.LoopExitNode = successor; } var forNode = new ControlFlowGraphNode(this.Summary); this.ISuccessors.Add(forNode); forNode.IPredecessors.Add(this); if (stmt.Statement is BlockSyntax) { forNode.Construct((stmt.Statement as BlockSyntax).Statements, 0, false, this); } else { forNode.Construct(new SyntaxList<StatementSyntax> { stmt.Statement }, 0, false, this); } }
private IEnumerable<ITypeSymbol> InferTypeInForStatement(ForStatementSyntax forStatement, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null) { // If we have a position, it has to be after "for(...;" if (previousToken.HasValue && previousToken.Value != forStatement.FirstSemicolonToken) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } if (expressionOpt != null && forStatement.Condition != expressionOpt) { return SpecializedCollections.EmptyEnumerable<ITypeSymbol>(); } return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Boolean)); }
private static IEnumerable<ISymbol> LoopCounters(ForStatementSyntax node, SemanticModel semanticModel) { var declaredVariables = node.Declaration == null ? Enumerable.Empty<ISymbol>() : node.Declaration.Variables .Select(v => semanticModel.GetDeclaredSymbol(v)) .Where(symbol => symbol != null); var initializedVariables = node.Initializers .Where(i => i.IsKind(SyntaxKind.SimpleAssignmentExpression)) .Select(i => semanticModel.GetSymbolInfo(((AssignmentExpressionSyntax)i).Left).Symbol); return declaredVariables.Union(initializedVariables); }
private static double ComputeWeightedDistance(ForStatementSyntax left, ForStatementSyntax right) { double statementDistance = ComputeDistance(left.Statement, right.Statement); double conditionDistance = ComputeDistance(left.Condition, right.Condition); double incDistance = ComputeDistance( GetDescendantTokensIgnoringSeparators(left.Incrementors), GetDescendantTokensIgnoringSeparators(right.Incrementors)); double distance = conditionDistance * 0.3 + incDistance * 0.3 + statementDistance * 0.4; double localsDistance; if (TryComputeLocalsDistance(left.Declaration, right.Declaration, out localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } return distance; }
public override SyntaxNode VisitForStatement(ForStatementSyntax node) { SyntaxNode rewrittenNode = null; if (node.Statement != null) rewrittenNode = RewriteWithBlockIfRequired(node, node.Statement); return base.VisitForStatement((ForStatementSyntax)rewrittenNode ?? node); }
private static SyntaxToken GetFirstIncludedToken(StatementSyntax statement, bool inRecursiveCall = false) { Debug.Assert(statement != null); switch (statement.Kind()) { case SyntaxKind.Block: return(((BlockSyntax)statement).OpenBraceToken); case SyntaxKind.BreakStatement: return(((BreakStatementSyntax)statement).BreakKeyword); case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return(((CheckedStatementSyntax)statement).Keyword); case SyntaxKind.ContinueStatement: return(((ContinueStatementSyntax)statement).ContinueKeyword); case SyntaxKind.ExpressionStatement: case SyntaxKind.LocalDeclarationStatement: return(statement.GetFirstToken()); case SyntaxKind.DoStatement: return(((DoStatementSyntax)statement).DoKeyword); case SyntaxKind.EmptyStatement: return(default(SyntaxToken)); //The caller will have to check for this. case SyntaxKind.FixedStatement: return(((FixedStatementSyntax)statement).FixedKeyword); case SyntaxKind.ForEachStatement: // NB: iteration variable is only in scope in body. ForEachStatementSyntax forEachSyntax = (ForEachStatementSyntax)statement; if (inRecursiveCall) { return(forEachSyntax.ForEachKeyword); } return(GetFirstIncludedToken(forEachSyntax.Statement, inRecursiveCall: true)); case SyntaxKind.ForStatement: // Section 8.8.3 of the spec says that the scope of the loop variable starts at // its declaration. If it's not there, then the scope we are interested in is // the loop body. ForStatementSyntax forSyntax = (ForStatementSyntax)statement; if (inRecursiveCall) { return(forSyntax.ForKeyword); } VariableDeclarationSyntax declOpt = forSyntax.Declaration; return(declOpt == null?GetFirstIncludedToken(forSyntax.Statement, inRecursiveCall : true) : declOpt.GetFirstToken()); case SyntaxKind.GotoDefaultStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoStatement: return(((GotoStatementSyntax)statement).GotoKeyword); case SyntaxKind.IfStatement: return(((IfStatementSyntax)statement).IfKeyword); case SyntaxKind.LabeledStatement: return(((LabeledStatementSyntax)statement).Identifier); case SyntaxKind.LockStatement: return(((LockStatementSyntax)statement).LockKeyword); case SyntaxKind.ReturnStatement: return(((ReturnStatementSyntax)statement).ReturnKeyword); case SyntaxKind.SwitchStatement: return(((SwitchStatementSyntax)statement).OpenBraceToken); case SyntaxKind.ThrowStatement: return(((ThrowStatementSyntax)statement).ThrowKeyword); case SyntaxKind.TryStatement: return(((TryStatementSyntax)statement).TryKeyword); case SyntaxKind.UnsafeStatement: return(((UnsafeStatementSyntax)statement).UnsafeKeyword); case SyntaxKind.UsingStatement: return(((UsingStatementSyntax)statement).UsingKeyword); case SyntaxKind.WhileStatement: return(((WhileStatementSyntax)statement).WhileKeyword); case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: return(((YieldStatementSyntax)statement).YieldKeyword); default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } }
private bool AnalyzeForStatement(ForStatementSyntax forStatement) => !forStatement.Statement.IsKind(SyntaxKind.Block);
public override void VisitForStatement(ForStatementSyntax node) => CheckNesting(node.ForKeyword, () => base.VisitForStatement(node));