Пример #1
0
        public override SyntaxNode VisitForEachStatement(ForEachStatementSyntax node)
        {
            if (node.Identifier.ToString() == renameFrom.ToString())
                node = node.WithIdentifier(renameTo);

            return base.VisitForEachStatement(node);
        }
Пример #2
0
        public override SyntaxList <StatementSyntax> VisitForEachStatement(CSS.ForEachStatementSyntax node)
        {
            VisualBasicSyntaxNode variable;

            if (node.Type.IsVar)
            {
                variable = SyntaxFactory.IdentifierName(CommonConversions.ConvertIdentifier(node.Identifier));
            }
            else
            {
                variable = SyntaxFactory.VariableDeclarator(
                    SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(CommonConversions.ConvertIdentifier(node.Identifier))),
                    SyntaxFactory.SimpleAsClause((TypeSyntax)node.Type.Accept(_nodesVisitor)),
                    null
                    );
            }
            var expression = (ExpressionSyntax)node.Expression.Accept(_nodesVisitor);
            var stmt       = ConvertBlock(node.Statement);
            var block      = SyntaxFactory.ForEachBlock(
                SyntaxFactory.ForEachStatement(variable, expression),
                stmt,
                SyntaxFactory.NextStatement()
                );

            return(SyntaxFactory.SingletonList <StatementSyntax>(block));
        }
Пример #3
0
        public override void VisitForEachStatement(ForEachStatementSyntax foreachStatement)
        {
            var expression = $"foreach ({foreachStatement.Type} {foreachStatement.Identifier} in {foreachStatement.InKeyword})";
            var token = CreateBlock(expression, SDNodeRole.ForEach);
            _tokenList.Add(token);

            VisitChildren(token.Statements, foreachStatement.Statement);
        }
Пример #4
0
        public static ForEachStatementSyntax AddBraces(ForEachStatementSyntax forEachStatement)
        {
            Debug.Assert(forEachStatement != null && NeedsBraces(forEachStatement));

            return forEachStatement
                .WithStatement(SyntaxFactory.Block(forEachStatement.Statement))
                .WithAdditionalAnnotations(Formatter.Annotation);
        }
        public override void VisitForEachStatement(ForEachStatementSyntax node)
        {
            if (!(node.Statement is BlockSyntax))
            {
                CreateAuditVariable(node.Statement);
            }

            base.VisitForEachStatement(node);
        }
        internal ForeachCollectionProducerBlock(ForEachStatementSyntax foreachNode, Block successor)
            : base(successor)
        {
            if (foreachNode == null)
            {
                throw new ArgumentNullException(nameof(foreachNode));
            }

            ForeachNode = foreachNode;
        }
            public override SyntaxNode VisitForEachStatement(ForEachStatementSyntax node)
            {
                node = (ForEachStatementSyntax)base.VisitForEachStatement(node);

                if (!node.Statement.IsKind(SyntaxKind.Block))
                {
                    this.addedAnnotations = true;
                    node = node.WithStatement(SyntaxFactory.Block(node.Statement));
                }

                return node;
            }
        private static SyntaxNode CalculateNewRoot(SyntaxNode root, ForEachStatementSyntax foreachSyntax, SemanticModel semanticModel)
        {
            var collection = foreachSyntax.Expression;
            var typeName = foreachSyntax.Type.ToString();
            var invocationToAdd = GetOfTypeInvocation(typeName, collection);
            var namedTypes = semanticModel.LookupNamespacesAndTypes(foreachSyntax.SpanStart).OfType<INamedTypeSymbol>();
            var isUsingAlreadyThere = namedTypes.Any(nt => nt.ToDisplayString() == ofTypeExtensionClass);

            if (isUsingAlreadyThere)
            {
                return root
                    .ReplaceNode(collection, invocationToAdd)
                    .WithAdditionalAnnotations(Formatter.Annotation);
            }
            else
            {
                var usingDirectiveToAdd = SyntaxFactory.UsingDirective(
                    SyntaxFactory.QualifiedName(
                        SyntaxFactory.IdentifierName("System"),
                        SyntaxFactory.IdentifierName("Linq")));

                var annotation = new SyntaxAnnotation("CollectionToChange");
                var newRoot = root.ReplaceNode(
                    collection,
                    collection.WithAdditionalAnnotations(annotation));

                var node = newRoot.GetAnnotatedNodes(annotation).First();
                var closestNamespaceWithUsing = node.AncestorsAndSelf()
                    .OfType<NamespaceDeclarationSyntax>()
                    .FirstOrDefault(n => n.Usings.Count > 0);

                if (closestNamespaceWithUsing != null)
                {
                    newRoot = newRoot.ReplaceNode(
                        closestNamespaceWithUsing,
                        closestNamespaceWithUsing.AddUsings(usingDirectiveToAdd))
                        .WithAdditionalAnnotations(Formatter.Annotation);
                }
                else
                {
                    var compilationUnit = node.FirstAncestorOrSelf<CompilationUnitSyntax>();
                    newRoot = compilationUnit.AddUsings(usingDirectiveToAdd);
                }

                node = newRoot.GetAnnotatedNodes(annotation).First();
                return newRoot
                    .ReplaceNode(node, invocationToAdd)
                    .WithAdditionalAnnotations(Formatter.Annotation);
            }
        }
        public override void VisitForEachStatement(ForEachStatementSyntax node)
        {
            foreach (var invocation in node.DescendantNodes().OfType<InvocationExpressionSyntax>())
            {
                var symbol = (IMethodSymbol)SemanticModel.GetSymbolInfo(invocation).Symbol;
                if (symbol != null && symbol.IsTaskCreationMethod())
                {
                    Logs.TempLog2.Info("{0}{1}--------------------------", Document.FilePath, node.Parent.ToLog());
                    break;
                }
                if (symbol != null && symbol.IsThreadStart())
                {
                    Logs.TempLog5.Info("{0}{1}--------------------------", Document.FilePath, node.Parent.ToLog());
                    break;
                }

            }
            base.VisitForEachStatement(node);
        }
Пример #10
0
        public override SyntaxList <StatementSyntax> VisitForEachStatement(CSS.ForEachStatementSyntax node)
        {
            VisualBasicSyntaxNode variable;

            if (node.Type.IsVar)
            {
                variable = SyntaxFactory.IdentifierName(_commonConversions.ConvertIdentifier(node.Identifier));
            }
            else
            {
                variable = SyntaxFactory.VariableDeclarator(
                    SyntaxFactory.SingletonSeparatedList(
                        SyntaxFactory.ModifiedIdentifier(_commonConversions.ConvertIdentifier(node.Identifier))),
                    SyntaxFactory.SimpleAsClause((TypeSyntax)node.Type.Accept(_nodesVisitor)),
                    null
                    );
            }

            return(CreateForEachStatement(variable, node.Expression, node.Statement));
        }
        private static bool TrySearchForIfThenContinueStatement(ForEachStatementSyntax fe, out IfStatementSyntax ifStatement, out string ifType)
        {
            if (fe.Statement is BlockSyntax)
            {
                var block = ((BlockSyntax)fe.Statement);
                if ((block.Statements.Count > 1 && block.Statements.First() is IfStatementSyntax) ||
                    (block.Statements.Count > 0 && block.Statements.First() is IfStatementSyntax && ((IfStatementSyntax)block.Statements.First()).Else != null)                    )
                {
                    ifStatement = (block.Statements.FirstOrDefault() as IfStatementSyntax);
                    if (ifStatement?.Statement is ContinueStatementSyntax || 
                        ((ifStatement?.Statement as BlockSyntax)?.Statements)?.FirstOrDefault() is ContinueStatementSyntax)
                    {
                        ifType = IfWithContinueToWhere;
                        return true;
                    }
                }
            }

            ifStatement = null;
            ifType = null;
            return false;
        }
        private async Task<Document> ConvertIfToLINQ(Document document, IfStatementSyntax ifStatement, ForEachStatementSyntax foreachStatement, CancellationToken c)
        {
            var generator = SyntaxGenerator.GetGenerator(document);

            var oldVariables = ifStatement.Condition.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().Where(x => x.Identifier.Text == foreachStatement.Identifier.Text);

            var whereCall = generator.InvocationExpression(
                generator.MemberAccessExpression(foreachStatement.Expression, "Where"),
                generator.Argument(
                    generator.ValueReturningLambdaExpression(
                        new[] { generator.LambdaParameter("x") }, 
                        ifStatement.Condition.ReplaceNodes(oldVariables, (x, y) => generator.IdentifierName("x")))));

            var root = await document.GetSyntaxRootAsync(c);

            var newFeStatement = foreachStatement
                .WithExpression((ExpressionSyntax)whereCall)
                .WithStatement(ifStatement.Statement.WithAdditionalAnnotations(Formatter.Annotation));

            var newRoot = root.ReplaceNode(foreachStatement, newFeStatement);
            return document.WithSyntaxRoot(newRoot);
        }
 public sealed override void VisitForEachStatement(ForEachStatementSyntax node)
 {
     _builder.Add(node);
     base.VisitForEachStatement(node);
 }
Пример #14
0
        /// <summary>
        /// Handles the given foreach statement.
        /// </summary>
        /// <param name="stmt">Statement</param>
        /// <param name="successor">Successor</param>
        private void HandleForeachStatement(ForEachStatementSyntax stmt, ControlFlowGraphNode successor)
        {
            this.SyntaxNodes.Add(stmt.Expression);
            this.IsLoopHeadNode = true;

            if (successor != null)
            {
                this.ISuccessors.Add(successor);
                successor.IPredecessors.Add(this);
                this.LoopExitNode = successor;
            }

            var foreachNode = new ControlFlowGraphNode(this.Summary);
            this.ISuccessors.Add(foreachNode);
            foreachNode.IPredecessors.Add(this);

            if (stmt.Statement is BlockSyntax)
            {
                foreachNode.Construct((stmt.Statement as BlockSyntax).Statements, 0, false, this);
            }
            else
            {
                foreachNode.Construct(new SyntaxList<StatementSyntax> { stmt.Statement }, 0, false, this);
            }
        }
Пример #15
0
 public override void VisitForEachStatement(ForEachStatementSyntax node)
 {
     VisitCommonForEachStatement(node);
 }
 public ForEachStatementTranslation(ForEachStatementSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
 {
     Expression = syntax.Expression.Get<ExpressionTranslation>(this);
     Statement = syntax.Statement.Get<StatementTranslation>(this);
     Type = syntax.Type.Get<TypeTranslation>(this);
 }
Пример #17
0
        public override SyntaxNode VisitForEachStatement(ForEachStatementSyntax node)
        {
            var info = this._semanticModel.GetTypeInfo(node.Expression);

            if (info.IsEnumerable())
            {
                //Note:Here we use __idx${identifierName} as index
                _output.Write(node.ForEachKeyword, "for (var __idx${0} = 0; __idx${0} < ", node.Identifier.ValueText);
                VisitExpression(node.Expression);
                _output.Write(node.Identifier, ".length; __idx${0}++) ", node.Identifier.ValueText);
                _output.TrivialWriteLine('{');

                _output.IncreaseIndent();
                _output.Write(node.Identifier, "var {0} = ", node.Identifier.ValueText);
                Visit(node.Expression);
                _output.WriteLine(node.Identifier, "[__idx${0}];", node.Identifier.ValueText);

                this.Visit(node.Statement);
                this.AppendCompensateSemicolon(node.Statement);
                _output.DecreaseIndent();
                _output.TrivialWrite('}');
            }
            else
            {
                _output.Write(node.ForEachKeyword, "for (var {0} in ", node.Identifier.ValueText);
                VisitExpression(node.Expression);
                _output.TrivialWriteLine(") {");

                _output.IncreaseIndent();
                this.Visit(node.Statement);
                this.AppendCompensateSemicolon(node.Statement);
                _output.DecreaseIndent();

                _output.TrivialWrite('}');
            }

            return node;
        }
 /// <summary>
 /// Add sequence point |here|:
 /// 
 /// |foreach| (Type var in expr) { }
 /// </summary>
 /// <remarks>
 /// Hit once, before looping begins.
 /// </remarks>
 private void AddForEachKeywordSequencePoint(ForEachStatementSyntax forEachSyntax, ref BoundStatement result)
 {
     if (this.GenerateDebugInfo)
     {
         BoundSequencePointWithSpan foreachKeywordSequencePoint = new BoundSequencePointWithSpan(forEachSyntax, null, forEachSyntax.ForEachKeyword.Span);
         result = new BoundStatementList(forEachSyntax, ImmutableArray.Create<BoundStatement>(foreachKeywordSequencePoint, result));
     }
 }
        public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node)
        {
            BoundForEachStatement boundForEach = (BoundForEachStatement)GetUpperBoundNode(node);

            if (boundForEach == null)
            {
                return default(ForEachStatementInfo);
            }

            ForEachEnumeratorInfo enumeratorInfoOpt = boundForEach.EnumeratorInfoOpt;

            Debug.Assert(enumeratorInfoOpt != null || boundForEach.HasAnyErrors);

            if (enumeratorInfoOpt == null)
            {
                return default(ForEachStatementInfo);
            }

            // Even though we usually pretend to be using System.Collection.IEnumerable
            // for arrays, that doesn't make sense for pointer arrays since object
            // (the type of System.Collections.IEnumerator.Current) isn't convertible
            // to pointer types.
            if (enumeratorInfoOpt.ElementType.IsPointerType())
            {
                Debug.Assert(!enumeratorInfoOpt.CurrentConversion.IsValid);
                return default(ForEachStatementInfo);
            }

            // NOTE: we're going to list GetEnumerator, etc for array and string
            // collections, even though we know that's not how the implementation
            // actually enumerates them.
            return new ForEachStatementInfo(
                enumeratorInfoOpt.GetEnumeratorMethod,
                enumeratorInfoOpt.MoveNextMethod,
                (PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol,
                enumeratorInfoOpt.NeedsDisposeMethod ? (MethodSymbol)Compilation.GetSpecialTypeMember(SpecialMember.System_IDisposable__Dispose) : null,
                enumeratorInfoOpt.ElementType,
                boundForEach.ElementConversion,
                enumeratorInfoOpt.CurrentConversion);
        }
Пример #20
0
 public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node)
 {
     return GetForEachStatementInfo((CommonForEachStatementSyntax)node);
 }
Пример #21
0
        public override void VisitForEachStatement(ForEachStatementSyntax node)
        {
            Debug.Assert((object)_containingMemberOrLambda == _enclosing.ContainingMemberOrLambda);
            var patternBinder = new PatternVariableBinder(node.Expression, _enclosing);

            AddToMap(node.Expression, patternBinder);
            Visit(node.Expression, patternBinder);

            var binder = new ForEachLoopBinder(patternBinder, node);
            AddToMap(node, binder);

            VisitPossibleEmbeddedStatement(node.Statement, binder);
        }
        private static TextSpan GetActiveSpan(ForEachStatementSyntax node, ForEachPart part)
        {
            switch (part)
            {
                case ForEachPart.ForEach:
                    return node.ForEachKeyword.Span;

                case ForEachPart.VariableDeclaration:
                    return TextSpan.FromBounds(node.Type.SpanStart, node.Identifier.Span.End);

                case ForEachPart.In:
                    return node.InKeyword.Span;

                case ForEachPart.Expression:
                    return node.Expression.Span;

                default:
                    throw ExceptionUtilities.UnexpectedValue(part);
            }
        }
        public override SyntaxNode VisitForEachStatement(ForEachStatementSyntax node)
        {
            SyntaxNode rewrittenNode = null;

            if (node.Statement != null)
                rewrittenNode = RewriteWithBlockIfRequired(node, node.Statement);

            return base.VisitForEachStatement((ForEachStatementSyntax)rewrittenNode ?? node);
        }
Пример #24
0
 public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node)
 {
     MemberSemanticModel memberModel = GetMemberModel(node);
     return memberModel == null ? default(ForEachStatementInfo) : memberModel.GetForEachStatementInfo(node);
 }
            public override SyntaxList <VB.Syntax.StatementSyntax> VisitForEachStatement(CS.Syntax.ForEachStatementSyntax node)
            {
                VB.Syntax.ForEachStatementSyntax begin = VB.SyntaxFactory.ForEachStatement(
                    VB.SyntaxFactory.IdentifierName(nodeVisitor.ConvertIdentifier(node.Identifier)),
                    nodeVisitor.VisitExpression(node.Expression));

                return(List <VB.Syntax.StatementSyntax>(
                           VB.SyntaxFactory.ForEachBlock(
                               begin,
                               Visit(node.Statement),
                               VB.SyntaxFactory.NextStatement())));
            }
Пример #26
0
 public BoundStatement BindForEach(ForEachStatementSyntax node, DiagnosticBag diagnostics)
 {
     Binder loopBinder = this.GetBinder(node);
     return loopBinder.BindForEachParts(diagnostics, loopBinder);
 }
            private IEnumerable<ITypeSymbol> InferTypeInForEachStatement(ForEachStatementSyntax forEachStatementSyntax, ExpressionSyntax expressionOpt = null, SyntaxToken? previousToken = null)
            {
                // If we have a position, then we have to be after "foreach(... in"
                if (previousToken.HasValue && previousToken.Value != forEachStatementSyntax.InKeyword)
                {
                    return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
                }

                if (expressionOpt != null && expressionOpt != forEachStatementSyntax.Expression)
                {
                    return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
                }

                // foreach (int v = Foo())
                var variableTypes = GetTypes(forEachStatementSyntax.Type);
                if (!variableTypes.Any())
                {
                    return SpecializedCollections.SingletonEnumerable(
                        this.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T)
                        .Construct(Compilation.GetSpecialType(SpecialType.System_Object)));
                }

                var type = this.Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T);
                return variableTypes.Select(v => type.Construct(v));
            }
Пример #28
0
        public override void VisitForEachStatement(ForEachStatementSyntax node)
        {
            Debug.Assert((object)_method == _enclosing.ContainingMemberOrLambda);
            var binder = new ForEachLoopBinder(_enclosing, node);
            AddToMap(node, binder);

            VisitPossibleEmbeddedStatement(node.Statement, binder);
        }
Пример #29
0
        /// <summary>
        /// Given a foreach statement, get the symbol for the iteration variable
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="forEachStatement"></param>
        public ILocalSymbol GetDeclaredSymbol(ForEachStatementSyntax forEachStatement, CancellationToken cancellationToken = default(CancellationToken))
        {
            Binder enclosingBinder = this.GetEnclosingBinder(GetAdjustedNodePosition(forEachStatement));

            if (enclosingBinder == null)
            {
                return null;
            }

            Binder foreachBinder = enclosingBinder.GetBinder(forEachStatement);

            // Binder.GetBinder can fail in presence of syntax errors. 
            if (foreachBinder == null)
            {
                return null;
            }

            LocalSymbol local = foreachBinder.GetDeclaredLocalsForScope(forEachStatement).FirstOrDefault();
            return ((object)local != null && local.DeclarationKind == LocalDeclarationKind.ForEachIterationVariable)
                ? local
                : null;
        }
 private static ForEachPart GetStatementPart(ForEachStatementSyntax node, int position)
 {
     return position < node.OpenParenToken.SpanStart ? ForEachPart.ForEach :
            position < node.InKeyword.SpanStart ? ForEachPart.VariableDeclaration :
            position < node.Expression.SpanStart ? ForEachPart.In :
            ForEachPart.Expression;
 }
Пример #31
0
 /// <summary>
 /// Gets for each statement info.
 /// </summary>
 /// <param name="node">The node.</param>
 public abstract ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node);
 private static bool AreEquivalentActiveStatements(ForEachStatementSyntax oldNode, ForEachStatementSyntax newNode)
 {
     // This is conservative, we might be able to allow changing the type.
     return AreEquivalentIgnoringLambdaBodies(oldNode.Type, newNode.Type)
         && AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression);
 }
        private static double ComputeWeightedDistance(ForEachStatementSyntax left, ForEachStatementSyntax right)
        {
            double statementDistance = ComputeDistance(left.Statement, right.Statement);
            double expressionDistance = ComputeDistance(left.Expression, right.Expression);
            double identifierDistance = ComputeDistance(left.Identifier, right.Identifier);

            double distance = identifierDistance * 0.7 + expressionDistance * 0.2 + statementDistance * 0.1;
            return AdjustForLocalsInBlock(distance, left.Statement, right.Statement, localsWeight: 0.6);
        }