예제 #1
0
        private void GenerateStatement(StatementSyntax statement)
        {
            var success = false;
            int mark = GetMark();

            switch (statement.Kind())
            {
                case SyntaxKind.LocalDeclarationStatement:
                    success = TryGenerateLocal((LocalDeclarationStatementSyntax)statement);
                    break;
                case SyntaxKind.Block:
                    success = true;
                    GenerateBlock((BlockSyntax)statement);
                    break;
                case SyntaxKind.ExpressionStatement:
                    success = TryGenerateExpressionStatement((ExpressionStatementSyntax)statement);
                    break;
            }

            if (!success)
            {
                Rewind(mark);
                GenerateUnknown(statement);
            }

            // Just for readability
            LineBreak();
        }
        private bool CheckStatement(SemanticModel semanticModel, StatementSyntax statement, CancellationToken cancellationToken)
        {
            if (statement is CheckedStatementSyntax ||
                statement is DoStatementSyntax ||
                statement is EmptyStatementSyntax ||
                statement is ExpressionStatementSyntax ||
                statement is FixedStatementSyntax ||
                statement is ForEachStatementSyntax ||
                statement is ForStatementSyntax ||
                statement is IfStatementSyntax ||
                statement is LocalDeclarationStatementSyntax ||
                statement is LockStatementSyntax ||
                statement is ReturnStatementSyntax ||
                statement is SwitchStatementSyntax ||
                statement is ThrowStatementSyntax ||
                statement is TryStatementSyntax ||
                statement is UnsafeStatementSyntax ||
                statement is UsingStatementSyntax ||
                statement is WhileStatementSyntax)
            {
                return true;
            }

            return false;
        }
예제 #3
0
        private static ExpressionSyntax TryGetExpression(StatementSyntax firstStatement)
        {
            if (firstStatement.Kind() == SyntaxKind.ExpressionStatement)
            {
                return ((ExpressionStatementSyntax)firstStatement).Expression;
            }
            else if (firstStatement.Kind() == SyntaxKind.ReturnStatement)
            {
                var returnStatement = (ReturnStatementSyntax)firstStatement;
                if (returnStatement.Expression != null)
                {
                    // If there are any comments on the return keyword, move them to
                    // the expression.
                    return firstStatement.GetLeadingTrivia().Any(t => t.IsSingleOrMultiLineComment())
                        ? returnStatement.Expression.WithLeadingTrivia(returnStatement.GetLeadingTrivia())
                        : returnStatement.Expression;
                }
            }
            else if (firstStatement.Kind() == SyntaxKind.ThrowStatement)
            {
                var throwStatement = (ThrowStatementSyntax)firstStatement;
                if (throwStatement.Expression != null)
                {
                    return SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression);
                }
            }

            return null;
        }
 public ControlFlowNode(StatementSyntax previousStatement, StatementSyntax nextStatement, ControlFlowNodeType type)
 {
     if (previousStatement == null && nextStatement == null)
         throw new ArgumentException("previousStatement and nextStatement must not be both null");
     this.PreviousStatement = previousStatement;
     this.NextStatement = nextStatement;
     this.Type = type;
 }
        internal static SyntaxNode AddStatementToConstructorBody(SyntaxNode root, ConstructorDeclarationSyntax constructor, StatementSyntax statement)
        {
            var body = constructor.Body ?? SyntaxFactory.Block();

            return root.ReplaceNode(root.GetCurrentNode(constructor), constructor.WithBody(
                    body.WithStatements(SyntaxFactory.List(new[] { statement }.Concat(body.Statements)))
                ));
        }
예제 #6
0
        private SyntaxNode GetStatementSingle(StatementSyntax statement)
        {
            var block = statement as BlockSyntax;

            return block == null ?
                statement :
                (block.Statements.Count == 1 ? block.Statements[0] : null);
        }
        public IfThrowPrecondition(StatementSyntax ifThrowStaement, ThrowStatementSyntax throwStatement)
        {
            Contract.Requires(ifThrowStaement != null);
            Contract.Requires(throwStatement != null);

            IfThrowStaement = ifThrowStaement;
            ThrowStatement = throwStatement;
        }
        private static void CheckLoop(SyntaxNodeAnalysisContext context, StatementSyntax statement)
        {
            if (IsNestedStatement(statement))
            {
                return;
            }

            CheckStatement(context, statement, "in a loop", "only once");
        }
 private static Document MakeObjectInitializer(Document document, SyntaxNode root, StatementSyntax statement, ISymbol variableSymbol, SemanticModel semanticModel)
 {
     var blockParent = statement.FirstAncestorOrSelf<BlockSyntax>();
     var objectCreationExpression = statement.DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
     var newBlockParent = CreateNewBlockParent(statement, semanticModel, objectCreationExpression, variableSymbol);
     var newRoot = root.ReplaceNode(blockParent, newBlockParent);
     var newDocument = document.WithSyntaxRoot(newRoot);
     return newDocument;
 }
예제 #10
0
        /// <summary>
        /// Creates a speculative SemanticModel for a method body that did not appear in the original source code.
        /// </summary>
        internal static MethodBodySemanticModel CreateSpeculative(SyntaxTreeSemanticModel parentSemanticModel, MethodSymbol owner, StatementSyntax syntax, Binder rootBinder, int position)
        {
            Debug.Assert(parentSemanticModel != null);
            Debug.Assert(syntax != null);
            Debug.Assert(rootBinder != null);
            Debug.Assert(rootBinder.IsSemanticModelBinder);

            return new MethodBodySemanticModel(parentSemanticModel.Compilation, owner, rootBinder, syntax, parentSemanticModel, position);
        }
        private static SwitchSectionSyntax CreateSection(SwitchLabelSyntax label, StatementSyntax statement)
        {
            var labels = new SyntaxList<SwitchLabelSyntax>();
            labels = labels.Add(label);

            return SyntaxFactory.SwitchSection(
                labels, CreateSectionStatements(statement)
                );
        }
예제 #12
0
        private Document ConvertToConditional(Document document, SemanticModel semanticModel, IfStatementSyntax ifStatement, StatementSyntax replacementStatement, CancellationToken cancellationToken)
        {
            var oldRoot = semanticModel.SyntaxTree.GetRoot();
            var newRoot = oldRoot.ReplaceNode(
                oldNode: ifStatement,
                newNode: replacementStatement.WithAdditionalAnnotations(Formatter.Annotation));

            return document.WithSyntaxRoot(newRoot);
        }
 private static ExpressionSyntax GetMemberAccessIdentifierFromStatements(SemanticModel semanticModel, StatementSyntax statementInsideIf, StatementSyntax statementInsideElse)
 {
     var expressionIf = statementInsideIf as ExpressionStatementSyntax;
     var expressionElse = statementInsideElse as ExpressionStatementSyntax;
     var memberAccessExpression = expressionIf != null && expressionElse != null
         ? GetMemberAccessExpressionFromAssignment(semanticModel, expressionIf.Expression as AssignmentExpressionSyntax, expressionElse.Expression as AssignmentExpressionSyntax)
         : GetMemberAccessExpressionFromReturn(statementInsideIf as ReturnStatementSyntax, statementInsideElse as ReturnStatementSyntax);
     return memberAccessExpression?.Expression;
 }
예제 #14
0
        private async Task<Document> MakeBlockAsync(Document document, StatementSyntax ifChildStatement, CancellationToken c)
        {
            var block = SyntaxFactory.Block(ifChildStatement);
            // Replace the old statement with the block:
            var root = await document.GetSyntaxRootAsync();
            var newRoot = root.ReplaceNode((SyntaxNode)ifChildStatement, block);

            var newDocument = document.WithSyntaxRoot(newRoot);
            return newDocument;
        }
        private static bool IsThrowArgumentExceptionStatement(StatementSyntax statement, SemanticModel semanticModel)
        {
            var throwStatement = statement as ThrowStatementSyntax;

            var objectCreation = throwStatement?.Expression as ObjectCreationExpressionSyntax;
            if (objectCreation == null) return false;

            var symbol = semanticModel.GetSymbolInfo(objectCreation.Type).Symbol;
            return symbol.IsArgumentExceptionType(semanticModel);
        }
 private static BlockSyntax CreateNewBlockParent(StatementSyntax statement, SemanticModel semanticModel, ObjectCreationExpressionSyntax objectCreationExpression, ISymbol variableSymbol)
 {
     var blockParent = statement.FirstAncestorOrSelf<BlockSyntax>();
     var assignmentExpressions = ObjectInitializerAnalyzer.FindAssignmentExpressions(semanticModel, statement, variableSymbol);
     var newBlockParent = SyntaxFactory.Block()
         .WithLeadingTrivia(blockParent.GetLeadingTrivia())
         .WithTrailingTrivia(blockParent.GetTrailingTrivia())
         .WithAdditionalAnnotations(Formatter.Annotation);
     var newAssignmentExpressions = new List<ExpressionStatementSyntax>();
     for (int i = 0; i < blockParent.Statements.Count; i++)
     {
         var blockStatement = blockParent.Statements[i];
         if (blockStatement.Equals(statement))
         {
             var initializationExpressions = new List<AssignmentExpressionSyntax>();
             foreach (var expressionStatement in assignmentExpressions)
             {
                 var assignmentExpression = expressionStatement.Expression as AssignmentExpressionSyntax;
                 var memberAccess = assignmentExpression.Left as MemberAccessExpressionSyntax;
                 var propertyIdentifier = memberAccess.Name as IdentifierNameSyntax;
                 initializationExpressions.Add(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, propertyIdentifier, assignmentExpression.Right));
             }
             var initializers = SyntaxFactory.SeparatedList<ExpressionSyntax>(initializationExpressions);
             var newObjectCreationExpression = objectCreationExpression.WithInitializer(
                 SyntaxFactory.InitializerExpression(
                     SyntaxKind.ObjectInitializerExpression,
                     SyntaxFactory.Token(SyntaxFactory.ParseLeadingTrivia(" "), SyntaxKind.OpenBraceToken, SyntaxFactory.ParseTrailingTrivia("\n")),
                     initializers,
                     SyntaxFactory.Token(SyntaxFactory.ParseLeadingTrivia(" "), SyntaxKind.CloseBraceToken, SyntaxFactory.ParseTrailingTrivia(""))
                 ))
                 .WithLeadingTrivia(objectCreationExpression.GetLeadingTrivia())
                 .WithTrailingTrivia(objectCreationExpression.GetTrailingTrivia())
                 .WithAdditionalAnnotations(Formatter.Annotation);
             if (newObjectCreationExpression.ArgumentList?.Arguments.Count == 0)
             {
                 newObjectCreationExpression = newObjectCreationExpression.WithArgumentList(null);
             }
             var newLocalDeclarationStatement = statement.ReplaceNode(objectCreationExpression, newObjectCreationExpression)
                 .WithLeadingTrivia(statement.GetLeadingTrivia())
                 .WithTrailingTrivia(statement.GetTrailingTrivia())
                 .WithAdditionalAnnotations(Formatter.Annotation);
             newBlockParent = newBlockParent.AddStatements(newLocalDeclarationStatement);
             i += initializationExpressions.Count;
         }
         else
         {
             newBlockParent = newBlockParent.AddStatements(blockStatement
                 .WithLeadingTrivia(blockStatement.GetLeadingTrivia())
                 .WithTrailingTrivia(blockStatement.GetTrailingTrivia())
                 .WithAdditionalAnnotations(Formatter.Annotation));
         }
     }
     return newBlockParent;
 }
예제 #17
0
 protected OperatorDeclarationSyntax CreateOperatorDeclaration(SyntaxKind kind, ParameterSyntax[] parameters, StatementSyntax statement)
 {
     return SyntaxFactory.OperatorDeclaration(
         new SyntaxList<AttributeListSyntax>(),
         SyntaxFactory.TokenList(new SyntaxToken[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword) }),
         SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)),
         SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
         SyntaxFactory.Token(kind),
         SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters)),
         SyntaxFactory.Block(statement),
         new SyntaxToken());
 }
 protected MethodDeclarationSyntax CreateSimpleMethodDeclaration(string name, StatementSyntax statement)
 {
     return SyntaxFactory.MethodDeclaration(
             new SyntaxList<AttributeListSyntax>(),
             SyntaxFactory.TokenList(new SyntaxToken[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword) }),
             SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)),
             null,
             SyntaxFactory.Identifier(name),
             null,
             SyntaxFactory.ParameterList(),
             new SyntaxList<TypeParameterConstraintClauseSyntax>(),
             SyntaxFactory.Block(statement),
             new SyntaxToken());
 }
예제 #19
0
        private static int GetNestingLevelStatement(StatementSyntax statement, MethodDeclarationSyntax methodDeclaration)
        {
            var nestingLevelStatement = IsEnlargersNesting(statement) ? 1 : 0;
            var parentStatement = statement.Parent;

            while (parentStatement != null && parentStatement != methodDeclaration)
            {
                if (IsEnlargersNesting(parentStatement))
                    nestingLevelStatement++;

                parentStatement = parentStatement.Parent;
            }
           
            return nestingLevelStatement;
        }
        private RegionAnalysisContext RegionAnalysisContext(StatementSyntax firstStatement, StatementSyntax lastStatement)
        {
            var memberModel = GetMemberModel(firstStatement);
            if (memberModel == null)
            {
                // Recover from error cases
                var node = new BoundBadStatement(firstStatement, ImmutableArray<BoundNode>.Empty, hasErrors: true);
                return new RegionAnalysisContext(Compilation, null, node, node, node);
            }

            Symbol member;
            BoundNode boundNode = GetBoundRoot(memberModel, out member);
            var first = memberModel.GetUpperBoundNode(firstStatement, promoteToBindable: true);
            var last = memberModel.GetUpperBoundNode(lastStatement, promoteToBindable: true);
            return new RegionAnalysisContext(Compilation, member, boundNode, first, last);
        }
예제 #21
0
 /// <summary>Creates a new ForStatementSyntax instance.</summary>
 public static ForStatementSyntax ForStatement(VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, ExpressionSyntax condition, SeparatedSyntaxList<ExpressionSyntax> incrementors, StatementSyntax statement)
 {
     return ForStatement(
         SyntaxFactory.Token(SyntaxKind.ForKeyword),
         SyntaxFactory.Token(SyntaxKind.OpenParenToken),
         default(SyntaxToken),
         null,
         declaration,
         initializers,
         SyntaxFactory.Token(SyntaxKind.SemicolonToken),
         condition,
         SyntaxFactory.Token(SyntaxKind.SemicolonToken),
         incrementors,
         SyntaxFactory.Token(SyntaxKind.CloseParenToken),
         statement);
 }
예제 #22
0
 /// <summary>Creates a new ForStatementSyntax instance.</summary>
 public static ForStatementSyntax ForStatement(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement)
 {
     return ForStatement(
         forKeyword: forKeyword,
         openParenToken: openParenToken,
         refKeyword: default(SyntaxToken),
         deconstruction: null,
         declaration: declaration,
         initializers: initializers,
         firstSemicolonToken: firstSemicolonToken,
         condition: condition,
         secondSemicolonToken: secondSemicolonToken,
         incrementors: incrementors,
         closeParenToken: closeParenToken,
         statement: statement);
 }
 internal static bool CheckForAssignmentOfLiteral(StatementSyntax statement, SyntaxKind literalExpressionType, out ExpressionSyntax assignmentTarget, out SyntaxTriviaList assignmentTrailingTriviaList)
 {
     assignmentTarget = null;
     assignmentTrailingTriviaList = SyntaxFactory.TriviaList(SyntaxFactory.SyntaxTrivia(SyntaxKind.DisabledTextTrivia, ""));
     var expressionStatement = statement as ExpressionStatementSyntax;
     if (expressionStatement == null)
         return false;
     var assignmentExpression = expressionStatement.Expression as AssignmentExpressionSyntax;
     if ((assignmentExpression == null) || !assignmentExpression.IsKind(SyntaxKind.SimpleAssignmentExpression))
         return false;
     assignmentTarget = assignmentExpression.Left as IdentifierNameSyntax;
     assignmentTrailingTriviaList = assignmentExpression.OperatorToken.TrailingTrivia;
     if (assignmentTarget == null)
         assignmentTarget = assignmentExpression.Left as MemberAccessExpressionSyntax;
     var rightAssignment = assignmentExpression.Right as LiteralExpressionSyntax;
     return (assignmentTarget != null) && (rightAssignment != null) && (rightAssignment.IsKind(literalExpressionType));
 }
예제 #24
0
        public static IEnumerable<ReplaceAction> GetSimplifications(ForEachStatementSyntax forLoop, ISemanticModel model, Assumptions assumptions, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (forLoop.IsAnyIterationSufficient(model, assumptions) == true)
                yield break; // a more appropriate code issue handles this case

            // can the loop be replaced by its first or last iteration?
            var isFirstSufficient = forLoop.IsFirstIterationSufficient(model, assumptions) == true;
            var isLastSufficient = forLoop.IsLastIterationSufficient(model, assumptions) == true;
            var firstVsLast = isFirstSufficient ? "First"
                            : isLastSufficient ? "Last"
                            : null;
            if (firstVsLast == null) yield break;

            // do we know how to translate?
            var loopStatements = forLoop.Statement.Statements();
            var rawThenStatements = loopStatements.SkipLast(loopStatements.Last().IsIntraLoopJump() ? 1 : 0).ToArray();
            if (rawThenStatements.Any(e => e.HasTopLevelIntraLoopJumps())) yield break; // don't know how to translate jumps that aren't at the end

            // wrap collection items in a type with a new null value (so that a null result definitively indicates an empty collection)
            var iteratorType = ((LocalSymbol)model.GetDeclaredSymbol(forLoop)).Type;
            var nuller = GetNullabledQueryAndValueGetter(iteratorType, forLoop.Identifier, forLoop.Expression);
            var nullableQuery = nuller.Item1;
            var valueGetter = nuller.Item2;
            var tempNullableLocalName = Syntax.Identifier("_" + forLoop.Identifier.ValueText);
            var tempNullableLocalGet = Syntax.IdentifierName(tempNullableLocalName);

            // build replacement
            var iteratorReads = forLoop.Statement.ReadsOfLocalVariable(forLoop.Identifier).ToArray();
            var desiredIterationQuery = nullableQuery.Accessing(firstVsLast + "OrDefault").Invoking();
            var condition = tempNullableLocalGet.BOpNotEquals(Syntax.LiteralExpression(SyntaxKind.NullLiteralExpression));
            var useDenulledLocal = iteratorReads.Length > 2;
            var thenStatement = useDenulledLocal
                              ? rawThenStatements.Prepend(forLoop.Identifier.VarInit(valueGetter(tempNullableLocalGet))).Block()
                              : rawThenStatements.Select(e => e.ReplaceNodes(iteratorReads, (n, a) => valueGetter(tempNullableLocalGet))).Block();
            var replacementStatements = new StatementSyntax[] {
                tempNullableLocalName.VarInit(desiredIterationQuery),
                condition.IfThen(thenStatement)
            };

            // expose as code action/issue
            yield return forLoop.MakeReplaceStatementWithManyAction(
                replacementStatements,
                "Execute " + firstVsLast + " if any");
        }
예제 #25
0
		private static async Task<Document> WrapAsync(Document document, StatementSyntax expressionStatement, CancellationToken token)
		{
			var identifierNameSyntax =
				expressionStatement.DescendantNodes().FirstOrDefault(x => x.IsKind(SyntaxKind.IdentifierName)) as
				IdentifierNameSyntax;

			if (identifierNameSyntax == null)
				return document;

			var loggerName = identifierNameSyntax.Identifier.Text;

			var expression = SyntaxFactory.ParseExpression(loggerName + ".IsDebugEnabled");
			var ifStatement = SyntaxFactory.IfStatement(expression, expressionStatement);

			var root = await document.GetSyntaxRootAsync(token);
			root = root.ReplaceNode(expressionStatement, ifStatement);

			return document.WithSyntaxRoot(root);
		}
 private static bool IsSelectingADifferentMethod(IEnumerable<SyntaxNode> childNodes, SimpleNameSyntax methodName, SyntaxTree tree, IMethodSymbol methodSymbol, StatementSyntax invocationStatement, Compilation compilation)
 {
     var parameterExpressions = CallExtensionMethodAsExtensionCodeFixProvider.GetParameterExpressions(childNodes);
     var firstArgument = parameterExpressions.FirstOrDefault();
     var argumentList = CallExtensionMethodAsExtensionCodeFixProvider.CreateArgumentListSyntaxFrom(parameterExpressions.Skip(1));
     var newInvocationStatement = SyntaxFactory.ExpressionStatement(
         CallExtensionMethodAsExtensionCodeFixProvider.CreateInvocationExpression(
             firstArgument, methodName, argumentList)).WithAdditionalAnnotations(introduceExtensionMethodAnnotation);
     var extensionMethodNamespaceUsingDirective = SyntaxFactory.UsingDirective(methodSymbol.ContainingNamespace.ToNameSyntax());
     var speculativeRootWithExtensionMethod = tree.GetCompilationUnitRoot()
         .ReplaceNode(invocationStatement, newInvocationStatement)
         .AddUsings(extensionMethodNamespaceUsingDirective);
     var speculativeModel = compilation.ReplaceSyntaxTree(tree, speculativeRootWithExtensionMethod.SyntaxTree)
         .GetSemanticModel(speculativeRootWithExtensionMethod.SyntaxTree);
     var speculativeInvocationStatement = speculativeRootWithExtensionMethod.SyntaxTree.GetCompilationUnitRoot().GetAnnotatedNodes(introduceExtensionMethodAnnotation).Single() as ExpressionStatementSyntax;
     var speculativeExtensionMethodSymbol = speculativeModel.GetSymbolInfo(speculativeInvocationStatement.Expression).Symbol as IMethodSymbol;
     var speculativeNonExtensionFormOfTheMethodSymbol = speculativeExtensionMethodSymbol?.GetConstructedReducedFrom();
     return speculativeNonExtensionFormOfTheMethodSymbol == null || !speculativeNonExtensionFormOfTheMethodSymbol.Equals(methodSymbol);
 }
        private static SyntaxNode CalculateNewRoot(SyntaxNode root, Diagnostic diagnostic,
            StatementSyntax currentAsStatement, AssignmentExpressionSyntax currentAsAssignment,
            BinaryExpressionSyntax currentAsBinary)
        {
            if (currentAsStatement != null)
            {
                return root.RemoveNode(currentAsStatement, SyntaxRemoveOptions.KeepNoTrivia);
            }

            if (currentAsAssignment != null)
            {
                return root.ReplaceNode(
                    currentAsAssignment,
                    currentAsAssignment.Left.WithAdditionalAnnotations(Formatter.Annotation));
            }

            var isReportingOnLeft = bool.Parse(diagnostic.Properties[SillyBitwiseOperation.IsReportingOnLeftKey]);
            return root.ReplaceNode(
                currentAsBinary,
                (isReportingOnLeft ? currentAsBinary.Right : currentAsBinary.Left).WithAdditionalAnnotations(Formatter.Annotation));
        }
예제 #28
0
        private bool IsCut(StatementSyntax statement, SyntaxToken identifier)
        {
            bool result = false;
            if (statement is IfStatementSyntax)
            {
                var ifStatement = (IfStatementSyntax)statement;
                if (ifStatement.Condition is BinaryExpressionSyntax)
                {
                    BinaryExpressionSyntax condition = (BinaryExpressionSyntax)ifStatement.Condition;

                    if (condition.Left.IsKind(SyntaxKind.NullLiteralExpression) ||
                        condition.Right.IsKind(SyntaxKind.NullLiteralExpression))
                    {
                        if (condition.Left is IdentifierNameSyntax)
                            result = ((IdentifierNameSyntax)condition.Left).Identifier.Text == identifier.Text;
                        else if (condition.Right is IdentifierNameSyntax)
                            result = ((IdentifierNameSyntax)condition.Right).Identifier.Text == identifier.Text;
                    }
                }
            }
            return result;
        }
        private static SyntaxList<StatementSyntax> CreateSectionStatements(StatementSyntax source)
        {
            var result = new SyntaxList<StatementSyntax>();

            if (source is BlockSyntax)
            {
                var block = source as BlockSyntax;
                result = result.AddRange(block.Statements);
            }
            else
            {
                result = result.Add(source);
            }

            var lastStatement = result.LastOrDefault();
            if (!(lastStatement is ReturnStatementSyntax || lastStatement is ThrowStatementSyntax))
            {
                result = result.Add(SyntaxFactory.BreakStatement());
            }

            return result;
        }
예제 #30
0
        internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out SemanticModel speculativeModel)
        {
            position = CheckAndAdjustPosition(position);

            var binder = this.GetEnclosingBinder(position);
            if (binder == null)
            {
                speculativeModel = null;
                return false;
            }

            var methodSymbol = (MethodSymbol)this.MemberSymbol;
            binder = new ExecutableCodeBinder(statement, methodSymbol, binder);

            // local declaration statements need to be wrapped in a block so the local gets seen 
            if (!statement.IsKind(SyntaxKind.Block))
            {
                binder = new BlockBinder(methodSymbol, binder, new SyntaxList<StatementSyntax>(statement));
            }

            speculativeModel = CreateSpeculative(parentModel, methodSymbol, statement, binder, position);
            return true;
        }
예제 #31
0
        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.FadeOutToken(FadeOutDescriptor, ifStatement.IfKeyword);
                        context.FadeOutToken(FadeOutDescriptor, ifStatement.OpenParenToken);
                        context.FadeOutToken(FadeOutDescriptor, ifStatement.CloseParenToken);
                        context.FadeOutNode(FadeOutDescriptor, ifStatement.Statement);

                        if (ifStatement.Else != null)
                        {
                            context.FadeOutNode(FadeOutDescriptor, @else);
                        }
                        else
                        {
                            context.FadeOutNode(FadeOutDescriptor, returnStatement2);
                        }
                    }
                }
            }
        }
        private static Task <Document> GetTransformedDocumentAsync(Document document, SyntaxNode root, StatementSyntax node, CancellationToken cancellationToken)
        {
            var newSyntaxRoot = root.ReplaceNode(node, SyntaxFactory.Block(node));

            return(Task.FromResult(document.WithSyntaxRoot(newSyntaxRoot)));
        }
예제 #33
0
 public LockStatementSyntax Update(SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement)
 => Update(AttributeLists, lockKeyword, openParenToken, expression, closeParenToken, statement);
예제 #34
0
        public void TestProperties()
        {
            var syntaxNode = this.CreateLocalFunctionStatement();

            Assert.True(syntaxNode.IsKind(SyntaxKind.LocalFunctionStatement));
            Assert.True(syntaxNode.IsKind(SyntaxKindEx.LocalFunctionStatement));

            var wrapper = (LocalFunctionStatementSyntaxWrapper)syntaxNode;

            Assert.Same(syntaxNode, wrapper.SyntaxNode);
            Assert.Equal(syntaxNode.Modifiers, wrapper.Modifiers);   // This is a struct, so we can't use Same()
            Assert.Same(syntaxNode.ReturnType, wrapper.ReturnType);
            Assert.Equal(syntaxNode.Identifier, wrapper.Identifier); // This is a struct, so we can't use Same()
            Assert.Same(syntaxNode.TypeParameterList, wrapper.TypeParameterList);
            Assert.Same(syntaxNode.ParameterList, wrapper.ParameterList);
            Assert.Equal(syntaxNode.ConstraintClauses, wrapper.ConstraintClauses); // This is a struct, so we can't use Same()
            Assert.Same(syntaxNode.Body, wrapper.Body);
            Assert.Same(syntaxNode.ExpressionBody, wrapper.ExpressionBody);
            Assert.True(syntaxNode.SemicolonToken.IsEquivalentTo(wrapper.SemicolonToken));

            var newModifiers = SyntaxFactory.TokenList();
            var wrapperWithModifiedModifiers = wrapper.WithModifiers(newModifiers);

            Assert.NotNull(wrapperWithModifiedModifiers.SyntaxNode);
            Assert.NotEqual(syntaxNode.Modifiers, wrapperWithModifiedModifiers.Modifiers);
            Assert.Equal(0, wrapperWithModifiedModifiers.Modifiers.Count);

            var newReturnType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword));
            var wrapperWithModifiedReturnType = wrapper.WithReturnType(newReturnType);

            Assert.NotNull(wrapperWithModifiedReturnType.SyntaxNode);
            Assert.NotSame(syntaxNode.ReturnType, wrapperWithModifiedReturnType.ReturnType);
            Assert.Equal(SyntaxKind.PredefinedType, wrapperWithModifiedReturnType.ReturnType.Kind());

            var newIdentifier = SyntaxFactory.Identifier("NewIdentifier");
            var wrapperWithModifiedIdentifier = wrapper.WithIdentifier(newIdentifier);

            Assert.NotNull(wrapperWithModifiedIdentifier.SyntaxNode);
            Assert.NotEqual(syntaxNode.Identifier, wrapperWithModifiedIdentifier.Identifier);
            Assert.Equal(SyntaxKind.IdentifierToken, wrapperWithModifiedIdentifier.Identifier.Kind());
            Assert.Equal("NewIdentifier", wrapperWithModifiedIdentifier.Identifier.Text);

            var newTypeParameterList = SyntaxFactory.TypeParameterList();
            var wrapperWithModifiedTypeParameterList = wrapper.WithTypeParameterList(newTypeParameterList);

            Assert.NotNull(wrapperWithModifiedTypeParameterList.SyntaxNode);
            Assert.NotSame(syntaxNode.TypeParameterList, wrapperWithModifiedTypeParameterList.TypeParameterList);
            Assert.Equal(0, wrapperWithModifiedTypeParameterList.TypeParameterList.Parameters.Count);

            var newParameterList = SyntaxFactory.ParameterList();
            var wrapperWithModifiedParameterList = wrapper.WithParameterList(newParameterList);

            Assert.NotNull(wrapperWithModifiedParameterList.SyntaxNode);
            Assert.NotSame(syntaxNode.ParameterList, wrapperWithModifiedParameterList.ParameterList);
            Assert.Equal(0, wrapperWithModifiedParameterList.ParameterList.Parameters.Count);

            var newConstraintClauses = SyntaxFactory.List <TypeParameterConstraintClauseSyntax>();
            var wrapperWithModifiedConstraintClauses = wrapper.WithConstraintClauses(newConstraintClauses);

            Assert.NotNull(wrapperWithModifiedConstraintClauses.SyntaxNode);
            Assert.NotEqual(syntaxNode.ConstraintClauses, wrapperWithModifiedConstraintClauses.ConstraintClauses);
            Assert.Equal(0, wrapperWithModifiedConstraintClauses.ConstraintClauses.Count);

            var newBody = SyntaxFactory.Block();
            var wrapperWithModifiedBody = wrapper.WithBody(newBody);

            Assert.NotNull(wrapperWithModifiedBody.SyntaxNode);
            Assert.Equal(SyntaxKind.Block, wrapperWithModifiedBody.Body.Kind());
            Assert.Equal(0, wrapperWithModifiedBody.Body.Statements.Count);

            var newExpressionBody = SyntaxFactory.ArrowExpressionClause(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
            var wrapperWithModifiedExpressionBody = wrapper.WithExpressionBody(newExpressionBody);

            Assert.NotNull(wrapperWithModifiedExpressionBody.SyntaxNode);
            Assert.Equal(SyntaxKind.ArrowExpressionClause, wrapperWithModifiedExpressionBody.ExpressionBody.Kind());
            Assert.Equal(SyntaxKind.NullLiteralExpression, wrapperWithModifiedExpressionBody.ExpressionBody.Expression.Kind());

            var newSemicolonToken = SyntaxFactory.Token(SyntaxKind.SemicolonToken).WithLeadingTrivia(SyntaxFactory.Space);
            var wrapperWithModifiedSemicolonToken = wrapper.WithSemicolonToken(newSemicolonToken);

            Assert.NotNull(wrapperWithModifiedSemicolonToken.SyntaxNode);
            Assert.Equal(1, wrapperWithModifiedSemicolonToken.SemicolonToken.LeadingTrivia.Count);
            Assert.Equal(" ", wrapperWithModifiedSemicolonToken.SemicolonToken.LeadingTrivia.ToString());

            var addedModifiers            = new SyntaxToken[] { SyntaxFactory.Token(SyntaxKind.AsyncKeyword) };
            var wrapperWithAddedModifiers = wrapper.AddModifiers(addedModifiers);

            Assert.NotNull(wrapperWithAddedModifiers.SyntaxNode);
            Assert.NotEqual(syntaxNode.Modifiers, wrapperWithAddedModifiers.Modifiers);
            Assert.Equal(2, wrapperWithAddedModifiers.Modifiers.Count);
            Assert.Equal(SyntaxKind.PrivateKeyword, wrapperWithAddedModifiers.Modifiers[0].Kind());
            Assert.Equal(SyntaxKind.AsyncKeyword, wrapperWithAddedModifiers.Modifiers[1].Kind());

            var addedTypeParameterList            = new TypeParameterSyntax[] { SyntaxFactory.TypeParameter("T2") };
            var wrapperWithAddedTypeParameterList = wrapper.AddTypeParameterListParameters(addedTypeParameterList);

            Assert.NotNull(wrapperWithAddedTypeParameterList.SyntaxNode);
            Assert.NotSame(syntaxNode.TypeParameterList, wrapperWithAddedTypeParameterList.TypeParameterList);
            Assert.Equal(2, wrapperWithAddedTypeParameterList.TypeParameterList.Parameters.Count);
            Assert.Equal("T1", wrapperWithAddedTypeParameterList.TypeParameterList.Parameters[0].Identifier.Text);
            Assert.Equal("T2", wrapperWithAddedTypeParameterList.TypeParameterList.Parameters[1].Identifier.Text);

            var addedParameterList            = new ParameterSyntax[] { SyntaxFactory.Parameter(SyntaxFactory.Identifier("param2")) };
            var wrapperWithAddedParameterList = wrapper.AddParameterListParameters(addedParameterList);

            Assert.NotNull(wrapperWithAddedParameterList.SyntaxNode);
            Assert.NotSame(syntaxNode.ParameterList, wrapperWithAddedParameterList.ParameterList);
            Assert.Equal(2, wrapperWithAddedParameterList.ParameterList.Parameters.Count);
            Assert.Equal("param1", wrapperWithAddedParameterList.ParameterList.Parameters[0].Identifier.Text);
            Assert.Equal("param2", wrapperWithAddedParameterList.ParameterList.Parameters[1].Identifier.Text);

            var addedConstraintClauses            = new TypeParameterConstraintClauseSyntax[] { SyntaxFactory.TypeParameterConstraintClause(SyntaxFactory.IdentifierName("constraint2")) };
            var wrapperWithAddedConstraintClauses = wrapper.AddConstraintClauses(addedConstraintClauses);

            Assert.NotNull(wrapperWithAddedConstraintClauses.SyntaxNode);
            Assert.NotEqual(syntaxNode.ConstraintClauses, wrapperWithAddedConstraintClauses.ConstraintClauses);
            Assert.Equal(2, wrapperWithAddedConstraintClauses.ConstraintClauses.Count);
            Assert.Equal("constraint1", wrapperWithAddedConstraintClauses.ConstraintClauses[0].Name.Identifier.Text);
            Assert.Equal("constraint2", wrapperWithAddedConstraintClauses.ConstraintClauses[1].Name.Identifier.Text);

            var addedBodyStatements            = new StatementSyntax[] { SyntaxFactory.ReturnStatement() };
            var wrapperWithAddedBodyStatements = wrapper.AddBodyStatements(addedBodyStatements);

            Assert.NotNull(wrapperWithAddedBodyStatements.SyntaxNode);
            Assert.Equal(SyntaxKind.Block, wrapperWithAddedBodyStatements.Body.Kind());
            Assert.Equal(2, wrapperWithAddedBodyStatements.Body.Statements.Count);
            Assert.Equal(SyntaxKind.BreakStatement, wrapperWithAddedBodyStatements.Body.Statements[0].Kind());
            Assert.Equal(SyntaxKind.ReturnStatement, wrapperWithAddedBodyStatements.Body.Statements[1].Kind());
        }
예제 #35
0
        private SyntaxNode GetNewBlock(SyntaxNode statement, StatementSyntax statementBody)
        {
            var body = SyntaxFactory.Block(statementBody);

            return(statement.ReplaceNode(statementBody, body));
        }
예제 #36
0
 private static bool HasDescendantCSharpStatement(this StatementSyntax c)
 {
     return(c.DescendantNodes().OfType <StatementSyntax>().Any());
 }
예제 #37
0
 private static StatementSyntax RemoveOrComment(StatementSyntax member)
 {
     return(member.WithLeadingTrivia(RemoveOrComment(member.GetLeadingTrivia())));
 }
 private static bool IsThrowStatementWithoutExpression(StatementSyntax statement)
 {
     return((statement is ThrowStatementSyntax throwStatement) &&
            throwStatement.Expression == null);
 }
 private static bool IsApprovedStatement(StatementSyntax statement)
 {
     return(!statement.IsAnyKind(ignoredStatementsInSwitch));
 }
예제 #40
0
        internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out SemanticModel speculativeModel)
        {
            position = CheckAndAdjustPosition(position);

            var binder = this.GetEnclosingBinder(position);

            if (binder == null)
            {
                speculativeModel = null;
                return(false);
            }

            var methodSymbol = (MethodSymbol)this.MemberSymbol;

            binder           = new ExecutableCodeBinder(statement, methodSymbol, binder);
            speculativeModel = CreateSpeculative(parentModel, methodSymbol, statement, binder, position);
            return(true);
        }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, StatementListSelection selectedStatements)
        {
            if (selectedStatements.Count <= 1)
            {
                return;
            }

            StatementSyntax firstStatement = selectedStatements.First();

            SemanticModel semanticModel = null;
            ISymbol       symbol        = null;
            ObjectCreationExpressionSyntax objectCreation = null;

            SyntaxKind kind = firstStatement.Kind();

            if (kind == SyntaxKind.LocalDeclarationStatement)
            {
                var localDeclaration = (LocalDeclarationStatementSyntax)firstStatement;

                VariableDeclaratorSyntax variable = localDeclaration
                                                    .Declaration?
                                                    .Variables
                                                    .SingleOrDefault(shouldThrow: false);

                objectCreation = variable?.Initializer?.Value as ObjectCreationExpressionSyntax;

                if (objectCreation != null)
                {
                    semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                    symbol = semanticModel.GetDeclaredSymbol(variable, context.CancellationToken);
                }
            }
            else if (kind == SyntaxKind.ExpressionStatement)
            {
                var expressionStatement = (ExpressionStatementSyntax)firstStatement;

                if (expressionStatement.Expression is AssignmentExpressionSyntax assignment)
                {
                    objectCreation = assignment.Right as ObjectCreationExpressionSyntax;

                    if (objectCreation != null)
                    {
                        semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                        symbol = semanticModel.GetSymbol(assignment.Left, context.CancellationToken);
                    }
                }
            }

            if (objectCreation == null)
            {
                return;
            }

            if (symbol?.IsErrorType() != false)
            {
                return;
            }

            for (int i = 1; i < selectedStatements.Count; i++)
            {
                if (!IsValidAssignmentStatement(selectedStatements[i], symbol, semanticModel, context.CancellationToken))
                {
                    return;
                }
            }

            context.RegisterRefactoring(
                "Collapse to initializer",
                ct => RefactorAsync(context.Document, objectCreation, selectedStatements, ct),
                RefactoringIdentifiers.CollapseToInitializer);
        }
예제 #42
0
 public static LockStatementSyntax LockStatement(SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement)
 => LockStatement(attributeLists: default, lockKeyword, openParenToken, expression, closeParenToken, statement);
 private static void Analyze(SyntaxNodeAnalysisContext context, SyntaxToken token, StatementSyntax statement)
 {
     if (!token.IsKind(SyntaxKind.None) &&
         !token.IsMissing &&
         statement?.IsKind(SyntaxKind.Block, SyntaxKind.EmptyStatement) == false &&
         context.SyntaxTree().IsSingleLineSpan(TextSpan.FromBounds(token.SpanStart, statement.SpanStart)))
     {
         ReportDiagnostic(context, statement);
     }
 }
예제 #44
0
 public static LabeledStatementSyntax LabeledStatement(
     SyntaxToken identifier,
     SyntaxToken colonToken,
     StatementSyntax statement
     ) => LabeledStatement(attributeLists: default, identifier, colonToken, statement);
예제 #45
0
 public UsingStatementSyntax Update(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement)
 {
     return(Update(awaitKeyword: default, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement));
            public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet <LabelSymbol> labelsOpt, StatementSyntax statementSyntax)
            {
                Debug.Assert(parent != null);
                Debug.Assert(statementSyntax != null);

                Debug.Assert(statementSyntax.Kind() == SyntaxKind.TryStatement ||
                             (statementSyntax.Kind() == SyntaxKind.UsingStatement && ((UsingStatementSyntax)statementSyntax).AwaitKeyword != default) ||
                             (statementSyntax.Kind() == SyntaxKind.ForEachStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) ||
                             (statementSyntax.Kind() == SyntaxKind.ForEachVariableStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default));

                this.ParentOpt      = parent;
                this.LabelsOpt      = labelsOpt;
                _statementSyntaxOpt = statementSyntax;
            }
예제 #47
0
        public static void AnalyzeWhileStatement(SyntaxNodeAnalysisContext context)
        {
            var whileStatement = (WhileStatementSyntax)context.Node;

            ExpressionSyntax condition = whileStatement.Condition;

            if (condition.IsMissing)
            {
                return;
            }

            if (!condition.IsSingleLine())
            {
                return;
            }

            StatementSyntax statement = whileStatement.Statement;

            if (!statement.IsKind(SyntaxKind.Block))
            {
                return;
            }

            var block = (BlockSyntax)statement;

            SyntaxList <StatementSyntax> innerStatements = block.Statements;

            if (innerStatements.Count <= 1)
            {
                return;
            }

            ExpressionSyntax incrementedExpression = GetIncrementedExpression(innerStatements.Last());

            if (!incrementedExpression.IsKind(SyntaxKind.IdentifierName))
            {
                return;
            }

            SyntaxList <StatementSyntax> outerStatements = SyntaxInfo.StatementListInfo(whileStatement).Statements;

            int index = outerStatements.IndexOf(whileStatement);

            if (index <= 0)
            {
                return;
            }

            SingleLocalDeclarationStatementInfo localInfo = GetLocalInfo(outerStatements[index - 1]);

            if (!localInfo.Success)
            {
                return;
            }

            if (index > 1)
            {
                SingleLocalDeclarationStatementInfo localInfo2 = GetLocalInfo(outerStatements[index - 2]);

                if (localInfo2.Success)
                {
                    ExpressionSyntax incrementedExpression2 = GetIncrementedExpression(innerStatements[innerStatements.Count - 2]);

                    if (incrementedExpression2.IsKind(SyntaxKind.IdentifierName))
                    {
                        var identifierName2 = (IdentifierNameSyntax)incrementedExpression2;

                        if (string.Equals(localInfo2.Identifier.ValueText, identifierName2.Identifier.ValueText, StringComparison.Ordinal))
                        {
                            return;
                        }
                    }
                }
            }

            var identifierName = (IdentifierNameSyntax)incrementedExpression;

            if (!string.Equals(localInfo.Identifier.ValueText, identifierName.Identifier.ValueText, StringComparison.Ordinal))
            {
                return;
            }

            if (ContainsContinueStatement())
            {
                return;
            }

            SemanticModel     semanticModel     = context.SemanticModel;
            CancellationToken cancellationToken = context.CancellationToken;

            ISymbol symbol = semanticModel.GetDeclaredSymbol(localInfo.Declarator, cancellationToken);

            if (symbol?.Kind != SymbolKind.Local)
            {
                return;
            }

            if (IsLocalVariableReferencedAfterWhileStatement())
            {
                return;
            }

            DiagnosticHelpers.ReportDiagnostic(context, DiagnosticDescriptors.UseForStatementInsteadOfWhileStatement, whileStatement.WhileKeyword);

            bool ContainsContinueStatement()
            {
                ContainsContinueStatementWalker walker = ContainsContinueStatementWalker.GetInstance();

                bool containsContinueStatement = false;

                foreach (StatementSyntax innerStatement in innerStatements)
                {
                    walker.Visit(innerStatement);

                    if (walker.ContainsContinueStatement)
                    {
                        containsContinueStatement = true;
                        break;
                    }
                }

                ContainsContinueStatementWalker.Free(walker);

                return(containsContinueStatement);
            }

            bool IsLocalVariableReferencedAfterWhileStatement()
            {
                ContainsLocalOrParameterReferenceWalker walker = ContainsLocalOrParameterReferenceWalker.GetInstance(symbol, semanticModel, cancellationToken);

                walker.VisitList(outerStatements, index + 1);

                return(ContainsLocalOrParameterReferenceWalker.GetResultAndFree(walker));
            }
        }
 public override IfStatementSyntax SetStatement(IfStatementSyntax statement, StatementSyntax newStatement)
 {
     return(statement.WithStatement(newStatement));
 }
예제 #49
0
 private static SingleLocalDeclarationStatementInfo GetLocalInfo(StatementSyntax statement)
 {
     return((statement.IsKind(SyntaxKind.LocalDeclarationStatement))
         ? SyntaxInfo.SingleLocalDeclarationStatementInfo((LocalDeclarationStatementSyntax)statement)
         : default);
예제 #50
0
 protected override StatementSyntax GetOrDeclareEntityArray(RoslynEcsTranslator.IterationContext iterationContext, out StatementSyntax arrayDisposal)
 {
     arrayDisposal = ExpressionStatement(
         InvocationExpression(
             MemberAccessExpression(
                 SyntaxKind.SimpleMemberAccessExpression,
                 IdentifierName(iterationContext.EntitiesArrayName),
                 IdentifierName(nameof(IDisposable.Dispose)))))
                     .NormalizeWhitespace();
     return(RoslynBuilder.DeclareLocalVariable(
                typeof(NativeArray <Entity>),
                iterationContext.EntitiesArrayName,
                ForEachContext.MakeInitEntityArray(iterationContext),
                RoslynBuilder.VariableDeclarationType.InferredType));
 }
예제 #51
0
 /// <summary>
 /// コンストラクタ
 /// </summary>
 /// <param name="method">メソッドインスタンス</param>
 /// <param name="statement">構文インスタンス</param>
 public BaseStatement(IMethod method, StatementSyntax statement)
 {
     MethodInstance = method;
     Statement      = statement;
 }
예제 #52
0
 public ForEachStatementSyntax Update(SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement)
 {
     return(Update(awaitKeyword: default, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement));
예제 #53
0
        internal void BuildLocals(Binder enclosingBinder, StatementSyntax statement, ArrayBuilder <LocalSymbol> locals)
        {
            var innerStatement = statement;

            // drill into any LabeledStatements -- atomic LabelStatements have been bound into
            // wrapped LabeledStatements by this point
            while (innerStatement.Kind() == SyntaxKind.LabeledStatement)
            {
                innerStatement = ((LabeledStatementSyntax)innerStatement).Statement;
            }

            switch (innerStatement.Kind())
            {
            case SyntaxKind.LocalDeclarationStatement:
            {
                Binder localDeclarationBinder = enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder;
                var    decl = (LocalDeclarationStatementSyntax)innerStatement;

                decl.Declaration.Type.VisitRankSpecifiers((rankSpecifier, args) =>
                    {
                        foreach (var expression in rankSpecifier.Sizes)
                        {
                            if (expression.Kind() != SyntaxKind.OmittedArraySizeExpression)
                            {
                                ExpressionVariableFinder.FindExpressionVariables(args.localScopeBinder, args.locals, expression, args.localDeclarationBinder);
                            }
                        }
                    }, (localScopeBinder: this, locals: locals, localDeclarationBinder: localDeclarationBinder));

                LocalDeclarationKind kind;
                if (decl.IsConst)
                {
                    kind = LocalDeclarationKind.Constant;
                }
                else if (decl.UsingKeyword != default(SyntaxToken))
                {
                    kind = LocalDeclarationKind.UsingVariable;
                }
                else
                {
                    kind = LocalDeclarationKind.RegularVariable;
                }
                foreach (var vdecl in decl.Declaration.Variables)
                {
                    var localSymbol = MakeLocal(decl.Declaration, vdecl, kind, localDeclarationBinder);
                    locals.Add(localSymbol);

                    // also gather expression-declared variables from the bracketed argument lists and the initializers
                    ExpressionVariableFinder.FindExpressionVariables(this, locals, vdecl, localDeclarationBinder);
                }
            }
            break;

            case SyntaxKind.ExpressionStatement:
            case SyntaxKind.IfStatement:
            case SyntaxKind.YieldReturnStatement:
            case SyntaxKind.ReturnStatement:
            case SyntaxKind.ThrowStatement:
            case SyntaxKind.GotoCaseStatement:
                ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(innerStatement) ?? enclosingBinder);
                break;

            case SyntaxKind.SwitchStatement:
                var switchStatement = (SwitchStatementSyntax)innerStatement;
                ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, enclosingBinder.GetBinder(switchStatement.Expression) ?? enclosingBinder);
                break;

            case SyntaxKind.LockStatement:
                Binder statementBinder = enclosingBinder.GetBinder(innerStatement);
                Debug.Assert(statementBinder != null);     // Lock always has a binder.
                ExpressionVariableFinder.FindExpressionVariables(this, locals, innerStatement, statementBinder);
                break;

            default:
                // no other statement introduces local variables into the enclosing scope
                break;
            }
        }
예제 #54
0
 public LabeledStatementSyntax Update(
     SyntaxToken identifier,
     SyntaxToken colonToken,
     StatementSyntax statement
     ) => Update(AttributeLists, identifier, colonToken, statement);
예제 #55
0
        internal 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());
            }
        }
예제 #56
0
 private static LiteralExpressionSyntax GetBooleanLiteral(StatementSyntax statement)
 {
     return(GetBooleanLiteral(GetReturnStatement(statement)));
 }
예제 #57
0
        protected override StatementSyntax AddMissingEventBuffers(RoslynEcsTranslator.IterationContext iterationContext, StatementSyntax onPopContext)
        {
            BlockSyntax b      = onPopContext is BlockSyntax bl ? bl : Block(onPopContext);
            var         before = new List <StatementSyntax>();

            foreach (Type eventType in iterationContext.WrittenEventTypes)
            {
                // ClearEvents<EventType>.AddMissingBuffers(<target query>, EntityManager);
                before.Add(ExpressionStatement(
                               InvocationExpression(
                                   MemberAccessExpression(
                                       SyntaxKind.SimpleMemberAccessExpression,
                                       GenericName(
                                           Identifier("EventSystem"))
                                       .WithTypeArgumentList(
                                           TypeArgumentList(
                                               SingletonSeparatedList(
                                                   eventType.ToTypeSyntax()))),
                                       IdentifierName("AddMissingBuffers")))
                               .WithArgumentList(
                                   ArgumentList(
                                       SeparatedList(
                                           new ArgumentSyntax[]
                {
                    Argument(IdentifierName("Entities")),
                    Argument(IdentifierName(SendEventTranslator.MakeMissingEventQueryName(iterationContext, eventType))),
                    Argument(IdentifierName("EntityManager"))
                })))));
            }

            b = b.WithStatements(b.Statements.InsertRange(0, before));
            return(b);
        }
예제 #58
0
        private static SyntaxToken GetFirstIncludedToken(StatementSyntax statement)
        {
            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:
            case SyntaxKind.ForEachVariableStatement:
                return(((CommonForEachStatementSyntax)statement).OpenParenToken.GetNextToken());

            case SyntaxKind.ForStatement:
                return(((ForStatementSyntax)statement).OpenParenToken.GetNextToken());

            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).Expression.GetFirstToken());

            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);

            case SyntaxKind.LocalFunctionStatement:
                return(statement.GetFirstToken());

            default:
                throw ExceptionUtilities.UnexpectedValue(statement.Kind());
            }
        }
 private static void ReportDiagnostic(SyntaxNodeAnalysisContext context, StatementSyntax statement)
 {
     context.ReportDiagnostic(
         DiagnosticDescriptors.FormatEmbeddedStatementOnSeparateLine,
         statement);
 }
예제 #60
0
        /// <summary>
        /// Creates a speculative SemanticModel for a method body that did not appear in the original source code.
        /// </summary>
        internal static MethodBodySemanticModel CreateSpeculative(SyntaxTreeSemanticModel parentSemanticModel, MethodSymbol owner, StatementSyntax syntax, Binder rootBinder, int position)
        {
            Debug.Assert(parentSemanticModel != null);
            Debug.Assert(syntax != null);
            Debug.Assert(rootBinder != null);
            Debug.Assert(rootBinder.IsSemanticModelBinder);

            return(new MethodBodySemanticModel(owner, rootBinder, syntax, parentSemanticModelOpt: parentSemanticModel, speculatedPosition: position));
        }