Esempio n. 1
0
 public override void VisitExpressionStatement(ExpressionStatementSyntax node)
 {
   // hack: Console.WriteLine
   var s = node.Expression.GetText().ToString().Trim();
   if (s.StartsWith("Console.WriteLine"))
   {
     var ise = node.Expression as InvocationExpressionSyntax;
     var args = ise.ArgumentList;
     cb.AppendWithIndent("cout << ")
       .Append(args.GetText().ToString().Trim('(', ')').Replace(" + ", " << ").Replace("+", " << "))
       .AppendLine(" << endl;");
   }
   else if (s.StartsWith("Environment.Exit"))
   {
     var ise = node.Expression as InvocationExpressionSyntax;
     var args = ise.ArgumentList;
     cb.AppendWithIndent("exit(")
       .Append(args.GetText().ToString().Trim('(', ')'))
       .AppendLine(");");
   }
   else
   {
     base.VisitExpressionStatement(node);
   }
 }
Esempio n. 2
0
        public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node)
        {
            var extension = null as SyntacticalExtension<SyntaxNode>;
            var expr = node.Expression;
            InvocationExpressionSyntax call = null;

            if (expr is InvocationExpressionSyntax)
                call = expr as InvocationExpressionSyntax;
            else if (expr is AssignmentExpressionSyntax)
            {
                var assignment = expr as AssignmentExpressionSyntax;
                call = assignment.Right as InvocationExpressionSyntax;
            }

            if (call != null)
                extension = codeExtension(call);

            if (extension != null)
            {

                if (extension.Kind != ExtensionKind.Code)
                {
                    //td: error, incorrect extension (i.e. a code extension being used inside a type)
                    return node;
                }

                _lookahead = CheckCodeExtension(node, extension);
                return null;
            }

            return node;
        }
Esempio n. 3
0
        /// <summary>
        /// Rewrites the statement with a raise statement.
        /// </summary>
        /// <param name="node">ExpressionStatementSyntax</param>
        /// <returns>SyntaxNode</returns>
        private SyntaxNode RewriteStatement(ExpressionStatementSyntax node)
        {
            var invocation = node.Expression as InvocationExpressionSyntax;

            var arguments = new List<ArgumentSyntax>();
            arguments.Add(invocation.ArgumentList.Arguments[0]);

            string payload = "";
            for (int i = 1; i < invocation.ArgumentList.Arguments.Count; i++)
            {
                if (i == invocation.ArgumentList.Arguments.Count - 1)
                {
                    payload += invocation.ArgumentList.Arguments[i].ToString();
                }
                else
                {
                    payload += invocation.ArgumentList.Arguments[i].ToString() + ", ";
                }
            }

            arguments[0] = SyntaxFactory.Argument(SyntaxFactory.ParseExpression(
                "new " + arguments[0].ToString() + "(" + payload + ")"));
            invocation = invocation.WithArgumentList(SyntaxFactory.ArgumentList(
                SyntaxFactory.SeparatedList(arguments)));

            var text = "{ " +
                node.WithExpression(invocation.WithExpression(SyntaxFactory.IdentifierName("this.Raise"))).ToString() +
                "return; }";
            var rewritten = SyntaxFactory.ParseStatement(text);
            rewritten = rewritten.WithTriviaFrom(node);

            return rewritten;
        }
		/// <summary>
		///     Normalizes the <paramref name="statement" /> if it is an invocation of a state machine method.
		/// </summary>
		public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax statement)
		{
			var invocationExpression = statement.Expression as InvocationExpressionSyntax;
			if (invocationExpression == null)
				return base.VisitExpressionStatement(statement);

			var methodSymbol = invocationExpression.GetReferencedSymbol(SemanticModel);
			if (!methodSymbol.IsStatic)
				return base.VisitExpressionStatement(statement);

			if (methodSymbol.Name != "InitialState" && methodSymbol.Name != "InitialStates" && methodSymbol.Name != "Transition")
				return base.VisitExpressionStatement(statement);

			var isComponentMethod = methodSymbol.ContainingType.Equals(Compilation.GetComponentClassSymbol());
			if (!isComponentMethod)
				return base.VisitExpressionStatement(statement);

			// MetadataBuilders.GetBuilder(this)
			var metadataBuilderSymbol = Syntax.TypeExpression(Compilation.GetTypeSymbol(typeof(MetadataBuilders)));
			var getBuilderMethod = Syntax.MemberAccessExpression(metadataBuilderSymbol, "GetBuilder");
			var builder = Syntax.InvocationExpression(getBuilderMethod, Syntax.ThisExpression());

			if (methodSymbol.Name == "Transition")
				return SyntaxFactory.Block(NormalizeTransitions(builder, invocationExpression)).NormalizeWhitespace().EnsureLineCount(statement);

			// .WithInitialStates(states)
			var withInitialStates = Syntax.MemberAccessExpression(builder, "WithInitialStates");
			var arguments = invocationExpression.ArgumentList.Arguments;
			return Syntax.ExpressionStatement(Syntax.InvocationExpression(withInitialStates, arguments)).EnsureLineCount(statement);
		}
		/// <summary>
		///     Normalizes the <paramref name="statement" /> if it is an invocation of a <c>SetInitialValues</c> method.
		/// </summary>
		public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax statement)
		{
			var invocationExpression = statement.Expression as InvocationExpressionSyntax;
			if (invocationExpression == null)
				return base.VisitExpressionStatement(statement);

			var methodSymbol = invocationExpression.GetReferencedSymbol(SemanticModel);
			if (methodSymbol.Name != "SetInitialValues" || !methodSymbol.IsStatic)
				return base.VisitExpressionStatement(statement);

			var isComponentMethod = methodSymbol.ContainingType.Equals(Compilation.GetComponentClassSymbol());
			var isFaultMethod = methodSymbol.ContainingType.Equals(Compilation.GetFaultClassSymbol());
			var isOccurrenceMethod = methodSymbol.ContainingType.Equals(Compilation.GetOccurrencePatternClassSymbol());

			if (!isComponentMethod && !isFaultMethod && !isOccurrenceMethod)
				return base.VisitExpressionStatement(statement);

			// MetadataBuilders.GetBuilder(this)
			var metadataBuilderSymbol = Syntax.TypeExpression(Compilation.GetTypeSymbol(typeof(MetadataBuilders)));
			var getBuilderMethod = Syntax.MemberAccessExpression(metadataBuilderSymbol, "GetBuilder");
			var builder = Syntax.InvocationExpression(getBuilderMethod, Syntax.ThisExpression());

			// ReflectionHelpers.GetField(typeof(...), typeof(...), "...")
			var fieldSymbol = invocationExpression.ArgumentList.Arguments[0].Expression.GetReferencedSymbol<IFieldSymbol>(SemanticModel);
			var fieldInfo = fieldSymbol.GetFieldInfoExpression(Syntax);

			// .WithInitialValues()
			var withInitialValues = Syntax.MemberAccessExpression(builder, Syntax.GenericName("WithInitialValues", fieldSymbol.Type));
			var arguments = new List<ArgumentSyntax>(invocationExpression.ArgumentList.Arguments.Skip(1));
			arguments.Insert(0, (ArgumentSyntax)Syntax.Argument(fieldInfo));
			return Syntax.ExpressionStatement(Syntax.InvocationExpression(withInitialValues, arguments)).EnsureLineCount(statement);
		}
		/// <summary>
		///   Normalizes the <paramref name="statement" />.
		/// </summary>
		public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax statement)
		{
			var transformed = TransformExpression(statement.Expression);
			if (transformed == null)
				return statement;

			return transformed.EnsureLineCount(statement);
		}
Esempio n. 7
0
        /// <summary>
        /// Rewrites the raise statement.
        /// </summary>
        /// <param name="node">ExpressionStatementSyntax</param>
        /// <returns>SyntaxNode</returns>
        private SyntaxNode RewriteStatement(ExpressionStatementSyntax node)
        {
            var text = "{ " + node.ToString() + "return; }";
            var rewritten = SyntaxFactory.ParseStatement(text);
            rewritten = rewritten.WithTriviaFrom(node);

            return rewritten;
        }
Esempio n. 8
0
            public override SyntaxList <StatementSyntax> VisitExpressionStatement(CSS.ExpressionStatementSyntax node)
            {
                var exprNode = node.Expression.Accept(nodesVisitor);

                if (!(exprNode is StatementSyntax))
                {
                    exprNode = SyntaxFactory.ExpressionStatement((ExpressionSyntax)exprNode);
                }

                return(SyntaxFactory.SingletonList((StatementSyntax)exprNode));
            }
 private static async Task<Document> UseExistenceOperatorAsyncWithAssignmentAsync(Document document, IfStatementSyntax ifStatement, CancellationToken cancellationToken, ExpressionStatementSyntax expressionIf)
 {
     var memberAccessAssignment = (AssignmentExpressionSyntax)expressionIf.Expression;
     var newMemberAccess = ((MemberAccessExpressionSyntax)memberAccessAssignment.Right).ToConditionalAccessExpression();
     var newExpressionStatement = SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, memberAccessAssignment.Left, newMemberAccess))
         .WithLeadingTrivia(ifStatement.GetLeadingTrivia())
         .WithTrailingTrivia(ifStatement.GetTrailingTrivia())
         .WithAdditionalAnnotations(Formatter.Annotation);
     var root = await document.GetSyntaxRootAsync(cancellationToken);
     var newRoot = root.ReplaceNode(ifStatement, newExpressionStatement);
     var newDocument = document.WithSyntaxRoot(newRoot);
     return newDocument;
 }
 private static void CheckForCondition(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocationNode,
   ExpressionStatementSyntax expressionStatementParent, DiagnosticDescriptor descriptor)
 {
   // Make sure the invocation's containing type is not the same as the class that contains it
   if ((invocationNode.DescendantNodesAndTokens().Any(_ => _.IsKind(SyntaxKind.DotToken)) &&
     !invocationNode.DescendantNodesAndTokens().Any(_ => _.IsKind(SyntaxKind.ThisExpression) || _.IsKind(SyntaxKind.BaseExpression))) &&
     (!expressionStatementParent?.DescendantNodesAndTokens()?.Any(_ => _.IsKind(SyntaxKind.EqualsToken)) ?? false) &&
     !(invocationNode.DescendantNodes()?.Any(_ => new ContainsInvocationExpressionWalker(_).HasIssue) ?? false) &&
     !FindSaveAssignmentIssueAnalyzer.IsReturnValue(invocationNode))
   {
     context.ReportDiagnostic(Diagnostic.Create(descriptor, invocationNode.GetLocation()));
   }
 }
 private static SyntaxNode CreateRootAddingDisposeToEndOfMethod(SyntaxNode root, ExpressionStatementSyntax statement, ILocalSymbol identitySymbol)
 {
     var method = statement.FirstAncestorOrSelf<MethodDeclarationSyntax>();
     var newDispose = ImplementsDisposableExplicitly(identitySymbol.Type)
         ? SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(
             SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
             SyntaxFactory.ParenthesizedExpression(SyntaxFactory.CastExpression(SyntaxFactory.ParseName("System.IDisposable").WithAdditionalAnnotations(Simplifier.Annotation), SyntaxFactory.IdentifierName(identitySymbol.Name))),
             SyntaxFactory.IdentifierName("Dispose"))))
         : SyntaxFactory.ParseStatement($"{identitySymbol.Name}.Dispose();");
     newDispose = newDispose.WithAdditionalAnnotations(Formatter.Annotation);
     var last = method.Body.Statements.Last();
     var newRoot = root.InsertNodesAfter(method.Body.Statements.Last(), new[] { newDispose });
     return newRoot;
 }
        public override void VisitExpressionStatement(ExpressionStatementSyntax node)
        {
            if (node.DescendantNodes().OfType<IdentifierNameSyntax>().Any(a => "WaitAll".Equals(a.ToString()))
                && node.Parent.ChildNodes().Any(a => a.ToString().Contains("StartNew"))
                && !node.Parent.ChildNodes().Any(a => a is ForStatementSyntax)
                && !node.Parent.ChildNodes().Any(a => a is ForEachStatementSyntax))
            {
                if (Id.ToLower().Contains("test"))
                    Helper.WriteInstance(InvokeTestFile, Id, node.Parent.ToString());
                else
                    Helper.WriteInstance(InvokeFile, Id, node.Parent.ToString());
            }

            base.VisitExpressionStatement(node);
        }
Esempio n. 13
0
        private async Task<Document> AssignMethodReturnToReceiverAsync(CodeFixContext context, Document document, ExpressionStatementSyntax statement, string receiverName, CancellationToken c)
        {
            var rValueExpr = statement.ToString();
            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken);
            var memberAccess = root.FindNode(context.Span)?.FirstAncestorOrSelf<MemberAccessExpressionSyntax>();

            var declaration = SyntaxFactory
                .ParseStatement($"{receiverName} = {rValueExpr}");

            var formattedDeclaration = declaration.WithTriviaFrom(statement);
            // Replace the old statement with the block:
            var newRoot = root.ReplaceNode((SyntaxNode)statement, formattedDeclaration);

            var newDocument = document.WithSyntaxRoot(newRoot);
            return newDocument;

        }
Esempio n. 14
0
        public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node)
        {
            SyntaxNode retVal = null;

            if (node.Expression.Kind() == SyntaxKind.AddAssignmentExpression ||
                node.Expression.Kind() == SyntaxKind.SubtractAssignmentExpression ||
                node.Expression.Kind() == SyntaxKind.MultiplyAssignmentExpression ||
                node.Expression.Kind() == SyntaxKind.DivideAssignmentExpression)
            {
                var add = node.Expression as BinaryExpressionSyntax;
                var printValueStmt = add.Left.GetText();

                retVal = base.VisitExpressionStatement(node);
            }

            return base.VisitExpressionStatement(node);
        }
Esempio n. 15
0
		/// <summary>
		///   Normalizes the <paramref name="statement" />.
		/// </summary>
		public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax statement)
		{
			if (!statement.Expression.IsKind(SyntaxKind.InvocationExpression))
				return statement;

			var expression = (InvocationExpressionSyntax)statement.Expression;
			var methodSymbol = expression.GetReferencedSymbol<IMethodSymbol>(SemanticModel);
			if (!methodSymbol.IsBindMethod(SemanticModel))
				return statement;

			var requiredPortReferenceExpression = (InvocationExpressionSyntax)expression.ArgumentList.Arguments[0].Expression;
			var providedPortReferenceExpression = (InvocationExpressionSyntax)expression.ArgumentList.Arguments[1].Expression;

			var requiredPorts = requiredPortReferenceExpression.ResolvePortReferences(SemanticModel);
			var providedPorts = providedPortReferenceExpression.ResolvePortReferences(SemanticModel);

			requiredPorts.RemoveWhere(symbol => !symbol.IsRequiredPort(SemanticModel));
			providedPorts.RemoveWhere(symbol => symbol.IsRequiredPort(SemanticModel));

			if (methodSymbol.Arity == 1)
			{
				var delegateType = (INamedTypeSymbol)methodSymbol.TypeArguments[0];
				MethodSymbolFilter.Filter(requiredPorts, delegateType);
				MethodSymbolFilter.Filter(providedPorts, delegateType);
			}
			else
				MethodSymbolFilter.Filter(requiredPorts, providedPorts);

			// The analyzer guarantees that there is exactly one port in each set now, but just to be sure...
			Assert.That(requiredPorts.Count == 1, "Expected exactly one required port at this point.");
			Assert.That(providedPorts.Count == 1, "Expected exactly one provided port at this point.");

			var requiredPortExpression = requiredPortReferenceExpression.ArgumentList.Arguments[0].Expression;
			var providedPortExpression = providedPortReferenceExpression.ArgumentList.Arguments[0].Expression;

			var requiredPortReference = CreatePortReference(requiredPorts.Single(), requiredPortExpression);
			var providedPortReference = CreatePortReference(providedPorts.Single(), providedPortExpression);

			var binderType = Syntax.TypeExpression(SemanticModel.GetTypeSymbol(typeof(PortBinding)));
			var binderInstance = Syntax.ObjectCreationExpression(binderType, requiredPortReference, providedPortReference);
			var bindMemberAccess = Syntax.MemberAccessExpression(binderInstance, nameof(PortBinding.Bind));
			var invocation = (ExpressionSyntax)Syntax.InvocationExpression(bindMemberAccess);

			return statement.WithExpression(invocation).NormalizeWhitespace().WithTrivia(statement).PrependLineDirective(statement.GetLineNumber());
		}
Esempio n. 16
0
        /// <summary>
        /// Rewrites the statement with a raise statement.
        /// </summary>
        /// <param name="node">ExpressionStatementSyntax</param>
        /// <returns>SyntaxNode</returns>
        private SyntaxNode RewriteStatement(ExpressionStatementSyntax node)
        {
            var invocation = node.Expression as InvocationExpressionSyntax;
            var arguments = new List<ArgumentSyntax>(invocation.ArgumentList.Arguments);

            arguments[0] = SyntaxFactory.Argument(SyntaxFactory.ParseExpression(
                "new " + arguments[0].ToString() + "()"));
            invocation = invocation.WithArgumentList(SyntaxFactory.ArgumentList(
                SyntaxFactory.SeparatedList(arguments)));
            
            var text = "{ " +
                node.WithExpression(invocation.WithExpression(SyntaxFactory.IdentifierName("this.Raise"))).ToString() +
                "return; }";
            var rewritten = SyntaxFactory.ParseStatement(text);
            rewritten = rewritten.WithTriviaFrom(node);

            return rewritten;
        }
		public override void VisitExpressionStatement(ExpressionStatementSyntax node)
		{
			if (this.InsideAutoIncludeMethodBlock)
			{
				var line = node.SyntaxTree.GetLineSpan(node.Span).StartLinePosition.Line;
				var allchildren = node.DescendantNodesAndTokens(descendIntoTrivia: true);
				if (allchildren.Any(a => a.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia))
				{
					var walker = new CodeWithDocumentationWalker(ClassDepth, line);
					walker.Visit(node.WithAdditionalAnnotations());
					this.Blocks.AddRange(walker.Blocks);
					return;
				}
				base.VisitExpressionStatement(node);
				this.Blocks.Add(new CodeBlock(node.WithoutLeadingTrivia().ToFullString(), line));
			}
			else base.VisitExpressionStatement(node);

		}
 public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node)
 {
     var aes = node.Expression as AssignmentExpressionSyntax;
     if (aes != null)
     {
         if (aes.Left is IdentifierNameSyntax && ((IdentifierNameSyntax)aes.Left).Identifier.Text == DocumentWeaver.RESULTMARKER)
         {
             foundAssignment = aes.Right;
             //to delete this statement
             return null;
         }
     }
     var ies = node.Expression as InvocationExpressionSyntax;
     if (ies != null)
     {
         var newNode = VisitInvocationExpression(ies);
         if (newNode == null) return null;
     }
     return base.VisitExpressionStatement(node);
 }
        private static async Task<Document> MakeMock(Document document, ExpressionStatementSyntax creation,
            CancellationToken cancellationToken)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var creationExpressionSyntax = creation.Expression.ChildNodes().OfType<ObjectCreationExpressionSyntax>().First();

            var symbolInfo = semanticModel.GetSymbolInfo(creationExpressionSyntax);

            var invokedSymbol = (IMethodSymbol)symbolInfo.CandidateSymbols.FirstOrDefault(x => x is IMethodSymbol
                                                                                               /*&& ((IMethodSymbol)x).Parameters.All(y => y.Type.IsAbstract)*/);

            var constructorParameters = invokedSymbol.Parameters.Select(x => new ConstructorParameters
            {
                ArgumentName = x.Name,
                TypeName = GetTypeNameFromType((INamedTypeSymbol)x.Type)
            }).ToArray();

            var changes = constructorParameters.MakeConstructorInjections();

            var changedDocument = await ChangesMaker.ApplyConstuctorInjections(document, creation, cancellationToken, changes, creationExpressionSyntax);
            return changedDocument;
        }
Esempio n. 20
0
 public BoundExpressionStatement BindExpressionStatement(ExpressionStatementSyntax node, DiagnosticBag diagnostics)
 {
     return BindExpressionStatement(node, node.Expression, node.AllowsAnyExpression, diagnostics);
 }
 public override SyntaxList <VB.Syntax.StatementSyntax> VisitExpressionStatement(CS.Syntax.ExpressionStatementSyntax node)
 {
     return(List(
                nodeVisitor.VisitStatement(node.Expression)));
 }
Esempio n. 22
0
 public static void WriteStatement(OutputWriter writer, ExpressionStatementSyntax statement)
 {
     writer.WriteIndent();
     Write(writer, statement.Expression);
     writer.Write(";\r\n");
 }
Esempio n. 23
0
 private bool TryGenerateExpressionStatement(ExpressionStatementSyntax expressionStatement)
 {
     using (ExpressionStatementTag(GetLineNumber(expressionStatement)))
     {
         return TryGenerateExpression(expressionStatement.Expression);
     }
 }
Esempio n. 24
0
 public override void VisitExpressionStatement(ExpressionStatementSyntax node)
 {
     Clear();
     base.VisitExpressionStatement(node);
 }
Esempio n. 25
0
 public override void VisitExpressionStatement(ExpressionStatementSyntax node)
 {
     Visit(node.Expression, _enclosing);
 }
 private static bool IsCorrectDispose(ExpressionStatementSyntax expressionStatement, SemanticModel semanticModel, ILocalSymbol identitySymbol)
 {
     if (expressionStatement == null) return false;
     var invocation = expressionStatement.Expression as InvocationExpressionSyntax;
     if (invocation?.ArgumentList.Arguments.Any() ?? true) return false;
     var memberAccess = invocation.Expression as MemberAccessExpressionSyntax;
     if (memberAccess == null) return false;
     ISymbol memberSymbol;
     if (memberAccess.Expression.IsKind(SyntaxKind.IdentifierName))
     {
         memberSymbol = semanticModel.GetSymbolInfo(memberAccess.Expression).Symbol;
     }
     else if (memberAccess.Expression.IsKind(SyntaxKind.ParenthesizedExpression))
     {
         var parenthesizedExpression = (ParenthesizedExpressionSyntax)memberAccess.Expression;
         var cast = parenthesizedExpression.Expression as CastExpressionSyntax;
         if (cast == null) return false;
         var catTypeSymbol = semanticModel.GetTypeInfo(cast.Type).Type;
         if (catTypeSymbol.SpecialType != SpecialType.System_IDisposable) return false;
         memberSymbol = semanticModel.GetSymbolInfo(cast.Expression).Symbol;
     }
     else return false;
     if (memberSymbol == null || !memberSymbol.Equals(identitySymbol)) return false;
     var memberAccessed = memberAccess.Name as IdentifierNameSyntax;
     if (memberAccessed == null) return false;
     if (memberAccessed.Identifier.Text != "Dispose" || memberAccessed.Arity != 0) return false;
     var methodSymbol = semanticModel.GetSymbolInfo(memberAccessed).Symbol as IMethodSymbol;
     if (methodSymbol == null) return false;
     if (methodSymbol.ToString() == "System.IDisposable.Dispose()") return true;
     var disposeMethod = (IMethodSymbol)semanticModel.Compilation.GetSpecialType(SpecialType.System_IDisposable).GetMembers("Dispose").Single();
     var isDispose = methodSymbol.Equals(methodSymbol.ContainingType.FindImplementationForInterfaceMember(disposeMethod));
     return isDispose;
 }
Esempio n. 27
0
        public static glsl.ExpressionStatementSyntax Translate(this cs.ExpressionStatementSyntax node)
        {
            var expression = new glsl.ExpressionStatementSyntax();

            return(expression.Update(node.Expression.Translate(), node.SemicolonToken));
        }
        private bool TryCheckSingleIfStatementForm(
            SyntaxNodeAnalysisContext syntaxContext,
            IfStatementSyntax ifStatement,
            BinaryExpressionSyntax condition,
            ExpressionStatementSyntax expressionStatement,
            InvocationExpressionSyntax invocationExpression)
        {
            var cancellationToken = syntaxContext.CancellationToken;

            // Look for the form:  "if (someExpr != null) someExpr()"
            if (condition.Left.IsKind(SyntaxKind.NullLiteralExpression) ||
                condition.Right.IsKind(SyntaxKind.NullLiteralExpression))
            {
                var expr = condition.Left.IsKind(SyntaxKind.NullLiteralExpression)
                    ? condition.Right
                    : condition.Left;

                cancellationToken.ThrowIfCancellationRequested();
                if (SyntaxFactory.AreEquivalent(expr, invocationExpression.Expression, topLevel: false))
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    // Looks good!
                    var tree = syntaxContext.SemanticModel.SyntaxTree;
                    var additionalLocations = new List<Location>
                    {
                        Location.Create(tree, ifStatement.Span),
                        Location.Create(tree, expressionStatement.Span)
                    };

                    var properties = ImmutableDictionary<string, string>.Empty.Add(Constants.Kind, Constants.SingleIfStatementForm);

                    syntaxContext.ReportDiagnostic(Diagnostic.Create(s_descriptor,
                        Location.Create(tree, TextSpan.FromBounds(ifStatement.SpanStart, expressionStatement.SpanStart)),
                        additionalLocations, properties));

                    if (expressionStatement.Span.End != ifStatement.Span.End)
                    {
                        syntaxContext.ReportDiagnostic(Diagnostic.Create(s_descriptor,
                            Location.Create(tree, TextSpan.FromBounds(expressionStatement.Span.End, ifStatement.Span.End)),
                            additionalLocations, properties));
                    }

                    return true;
                }
            }

            return false;
        }
 private static bool IsAssignedToField(ExpressionStatementSyntax expressionStatement, SemanticModel semanticModel, ILocalSymbol identitySymbol)
 {
     if (expressionStatement == null) return false;
     if (!expressionStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression)) return false;
     var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression;
     var assignmentTarget = semanticModel.GetSymbolInfo(assignment.Left).Symbol;
     if (assignmentTarget?.Kind != SymbolKind.Field) return false;
     var assignmentSource = semanticModel.GetSymbolInfo(assignment.Right).Symbol;
     return (identitySymbol.Equals(assignmentSource));
 }
        private bool TryCheckVariableAndIfStatementForm(
            SyntaxNodeAnalysisContext syntaxContext,
            IfStatementSyntax ifStatement,
            BinaryExpressionSyntax condition,
            ExpressionStatementSyntax expressionStatement,
            InvocationExpressionSyntax invocationExpression)
        {
            var cancellationToken = syntaxContext.CancellationToken;
            cancellationToken.ThrowIfCancellationRequested();

            // look for the form "if (a != null)" or "if (null != a)"
            if (!ifStatement.Parent.IsKind(SyntaxKind.Block))
            {
                return false;
            }

            if (!IsNullCheckExpression(condition.Left, condition.Right) &&
                !IsNullCheckExpression(condition.Right, condition.Left))
            {
                return false;
            }

            var expression = invocationExpression.Expression;
            if (!expression.IsKind(SyntaxKind.IdentifierName))
            {
                return false;
            }

            var conditionName = condition.Left is IdentifierNameSyntax
                ? (IdentifierNameSyntax)condition.Left
                : (IdentifierNameSyntax)condition.Right;

            var invocationName = (IdentifierNameSyntax)expression;
            if (!Equals(conditionName.Identifier.ValueText, invocationName.Identifier.ValueText))
            {
                return false;
            }

            // Now make sure the previous statement is "var a = ..."
            var parentBlock = (BlockSyntax)ifStatement.Parent;
            var ifIndex = parentBlock.Statements.IndexOf(ifStatement);
            if (ifIndex == 0)
            {
                return false;
            }

            var previousStatement = parentBlock.Statements[ifIndex - 1];
            if (!previousStatement.IsKind(SyntaxKind.LocalDeclarationStatement))
            {
                return false;
            }

            var localDeclarationStatement = (LocalDeclarationStatementSyntax)previousStatement;
            var variableDeclaration = localDeclarationStatement.Declaration;

            if (variableDeclaration.Variables.Count != 1)
            {
                return false;
            }

            var declarator = variableDeclaration.Variables[0];
            if (declarator.Initializer == null)
            {
                return false;
            }

            cancellationToken.ThrowIfCancellationRequested();
            if (!Equals(declarator.Identifier.ValueText, conditionName.Identifier.ValueText))
            {
                return false;
            }

            // Syntactically this looks good.  Now make sure that the local is a delegate type.
            var semanticModel = syntaxContext.SemanticModel;
            var localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken);

            // Ok, we made a local just to check it for null and invoke it.  Looks like something
            // we can suggest an improvement for!
            // But first make sure we're only using the local only within the body of this if statement.
            var analysis = semanticModel.AnalyzeDataFlow(localDeclarationStatement, ifStatement);
            if (analysis.ReadOutside.Contains(localSymbol) || analysis.WrittenOutside.Contains(localSymbol))
            {
                return false;
            }

            // Looks good!
            var tree = semanticModel.SyntaxTree;
            var additionalLocations = new List<Location>
            {
                Location.Create(tree, localDeclarationStatement.Span),
                Location.Create(tree, ifStatement.Span),
                Location.Create(tree, expressionStatement.Span)
            };

            var properties = ImmutableDictionary<string, string>.Empty.Add(Constants.Kind, Constants.VariableAndIfStatementForm);

            syntaxContext.ReportDiagnostic(Diagnostic.Create(s_descriptor,
                Location.Create(tree, TextSpan.FromBounds(localDeclarationStatement.SpanStart, expressionStatement.SpanStart)),
                additionalLocations, properties));

            if (expressionStatement.Span.End != ifStatement.Span.End)
            {
                syntaxContext.ReportDiagnostic(Diagnostic.Create(s_descriptor,
                    Location.Create(tree, TextSpan.FromBounds(expressionStatement.Span.End, ifStatement.Span.End)),
                    additionalLocations, properties));
            }

            return true;
        }
		public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node)
		{
			var expression = this.Visit(node.Expression);

			if (expression is IfStatementSyntax)
			{
				return expression;
			}
			else
			{
				var semicolonToken = this.VisitToken(node.SemicolonToken);

				return node.Update((ExpressionSyntax)expression, semicolonToken);
			}
		}
Esempio n. 32
0
 public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node)
 {
     this.Visit(node.Expression);
     return node;
 }
            private IEnumerable<ITypeSymbol> InferTypeInExpressionStatement(ExpressionStatementSyntax expressionStatement, SyntaxToken? previousToken = null)
            {
                // If we're position based, then that means we're after the semicolon.  In this case
                // we don't have any sort of type to infer.
                if (previousToken.HasValue)
                {
                    return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
                }

                return SpecializedCollections.SingletonEnumerable(this.Compilation.GetSpecialType(SpecialType.System_Void));
            }
Esempio n. 34
0
 public override SyntaxList <StatementSyntax> VisitExpressionStatement(CSS.ExpressionStatementSyntax node)
 {
     return(SyntaxFactory.SingletonList(ConvertSingleExpression(node.Expression)));
 }