private ISymbol GetMutatedSymbol(IDocument document, CancellationToken cancellationToken, ExpressionStatementSyntax expressionStatement) { if (expressionStatement.Expression.Kind != SyntaxKind.AssignExpression && expressionStatement.Expression.Kind != SyntaxKind.AddAssignExpression && expressionStatement.Expression.Kind != SyntaxKind.DivideAssignExpression && expressionStatement.Expression.Kind != SyntaxKind.MultiplyAssignExpression && expressionStatement.Expression.Kind != SyntaxKind.SubtractAssignExpression && expressionStatement.Expression.Kind != SyntaxKind.ModuloAssignExpression && expressionStatement.Expression.Kind != SyntaxKind.AndAssignExpression && expressionStatement.Expression.Kind != SyntaxKind.OrAssignExpression && expressionStatement.Expression.Kind != SyntaxKind.ExclusiveOrAssignExpression && expressionStatement.Expression.Kind != SyntaxKind.LeftShiftAssignExpression && expressionStatement.Expression.Kind != SyntaxKind.RightShiftAssignExpression) return null; var model = document.GetSemanticModel(cancellationToken); var binaryExpression = (BinaryExpressionSyntax)expressionStatement.Expression; var symbolInfo = model.GetSymbolInfo(binaryExpression.Left); return symbolInfo.Symbol; }
private BoundExpressionStatement BindExpressionStatement(ExpressionStatementSyntax syntax) { return new BoundExpressionStatement(Bind(syntax.Expression, BindExpression)); }
private static async Task <Document> ApplyFixAsync(CodeFixContext context, CancellationToken cancellationToken, ExpressionStatementSyntax statement, bool usesUnderscoreNames) { var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken) .ConfigureAwait(false); var containingType = statement.FirstAncestor <TypeDeclarationSyntax>(); var field = editor.AddField( containingType, usesUnderscoreNames ? "_disposable" : "disposable", Accessibility.Private, DeclarationModifiers.ReadOnly, CompositeDisposableType, cancellationToken); var fieldAccess = usesUnderscoreNames ? SyntaxFactory.IdentifierName(field.Name()) : SyntaxFactory.ParseExpression($"this.{field.Name()}"); editor.ReplaceNode( statement, SyntaxFactory.ExpressionStatement( (ExpressionSyntax)editor.Generator.AssignmentStatement( fieldAccess, ((ObjectCreationExpressionSyntax)editor.Generator.ObjectCreationExpression( CompositeDisposableType)) .WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SingletonSeparatedList( statement.Expression))))) .WithLeadingTrivia(SyntaxFactory.ElasticMarker) .WithTrailingTrivia(SyntaxFactory.ElasticMarker)); return(editor.GetChangedDocument()); }
private void RunExpressionStatement(ExpressionStatementSyntax node) { RunExpression(node.Expression); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { if (!Settings.IsAnyCodeFixEnabled( CodeFixIdentifiers.UseExplicitTypeInsteadOfVar, CodeFixIdentifiers.ReplaceVariableDeclarationWithAssignment)) { return; } SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); if (!TryFindFirstAncestorOrSelf(root, context.Span, out SyntaxNode node, predicate: f => f.IsKind( SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.Parameter, SyntaxKind.DeclarationPattern, SyntaxKind.DeclarationExpression))) { return; } if (node.IsKind(SyntaxKind.ForEachStatement, SyntaxKind.Parameter, SyntaxKind.DeclarationPattern, SyntaxKind.DeclarationExpression)) { return; } var variableDeclaration = (VariableDeclarationSyntax)node; foreach (Diagnostic diagnostic in context.Diagnostics) { switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.ImplicitlyTypedVariablesCannotHaveMultipleDeclarators: case CompilerDiagnosticIdentifiers.ImplicitlyTypedVariablesCannotBeConstant: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.UseExplicitTypeInsteadOfVar)) { return; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); TypeSyntax type = variableDeclaration.Type; ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); if (typeSymbol?.SupportsExplicitDeclaration() == true) { CodeAction codeAction = CodeAction.Create( $"Change type to '{SymbolDisplay.ToMinimalDisplayString(typeSymbol, semanticModel, type.SpanStart, SymbolDisplayFormats.Default)}'", cancellationToken => ChangeTypeRefactoring.ChangeTypeAsync(context.Document, type, typeSymbol, cancellationToken), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } break; } case CompilerDiagnosticIdentifiers.LocalVariableOrFunctionIsAlreadyDefinedInThisScope: case CompilerDiagnosticIdentifiers.LocalOrParameterCannotBeDeclaredInThisScopeBecauseThatNameIsUsedInEnclosingScopeToDefineLocalOrParameter: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.ReplaceVariableDeclarationWithAssignment)) { return; } if (!(variableDeclaration.Parent is LocalDeclarationStatementSyntax localDeclaration)) { return; } VariableDeclaratorSyntax variableDeclarator = variableDeclaration.Variables.SingleOrDefault(shouldThrow: false); if (variableDeclarator == null) { break; } ExpressionSyntax value = variableDeclarator.Initializer?.Value; if (value == null) { break; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); VariableDeclaratorSyntax variableDeclarator2 = FindVariableDeclarator( variableDeclarator.Identifier.ValueText, semanticModel.GetEnclosingSymbolSyntax(localDeclaration.SpanStart, context.CancellationToken)); if (variableDeclarator2?.SpanStart < localDeclaration.SpanStart) { CodeAction codeAction = CodeAction.Create( "Replace variable declaration with assignment", cancellationToken => { ExpressionStatementSyntax newNode = CSharpFactory.SimpleAssignmentStatement( SyntaxFactory.IdentifierName(variableDeclarator.Identifier), value); newNode = newNode .WithTriviaFrom(localDeclaration) .WithFormatterAnnotation(); return(context.Document.ReplaceNodeAsync(localDeclaration, newNode, cancellationToken)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } break; } } } }
public override bool VisitExpressionStatement(ExpressionStatementSyntax node) { return(Visit(node.Expression)); }
public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node) { SyntaxNode updatedNode = base.VisitExpressionStatement(node); if (node.Expression.Kind == SyntaxKind.AddAssignExpression || node.Expression.Kind == SyntaxKind.SubtractAssignExpression || node.Expression.Kind == SyntaxKind.MultiplyAssignExpression || node.Expression.Kind == SyntaxKind.DivideAssignExpression) { // Print value of the variable on the 'Left' side of // compound assignement statements encountered. var compoundAssignmentExpression = (BinaryExpressionSyntax)node.Expression; StatementSyntax consoleWriteLineStatement = Syntax.ParseStatement(string.Format("System.Console.WriteLine({0});", compoundAssignmentExpression.Left.ToString())); updatedNode = Syntax.Block(Syntax.List<StatementSyntax>( node.WithLeadingTrivia().WithTrailingTrivia(), // Remove leading and trailing trivia. consoleWriteLineStatement)) .WithLeadingTrivia(node.GetLeadingTrivia()) // Attach leading trivia from original node. .WithTrailingTrivia(node.GetTrailingTrivia()); // Attach trailing trivia from original node. } return updatedNode; }
private VariableState VisitExpressionStatement(ExpressionStatementSyntax node, ExecutionState state) { return(VisitExpression(node.Expression, state)); //Simply unwrap the expression }
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { WriteStart(""); base.VisitExpressionStatement(node); WriteLine(); }
private static ImmutableArray <IfAnalysis> Analyze( IfStatementSyntax ifStatement, ExpressionSyntax condition, ExpressionStatementSyntax expressionStatement1, ExpressionStatementSyntax expressionStatement2, IfAnalysisOptions options, SemanticModel semanticModel, CancellationToken cancellationToken) { SimpleAssignmentStatementInfo assignment1 = SyntaxInfo.SimpleAssignmentStatementInfo(expressionStatement1); if (!assignment1.Success) { return(Empty); } SimpleAssignmentStatementInfo assignment2 = SyntaxInfo.SimpleAssignmentStatementInfo(expressionStatement2); if (!assignment2.Success) { return(Empty); } ExpressionSyntax left1 = assignment1.Left; ExpressionSyntax left2 = assignment2.Left; ExpressionSyntax right1 = assignment1.Right; ExpressionSyntax right2 = assignment2.Right; if (!AreEquivalent(left1, left2)) { return(Empty); } if (options.UseCoalesceExpression || options.UseExpression) { SyntaxKind kind1 = right1.Kind(); SyntaxKind kind2 = right2.Kind(); if (IsBooleanLiteralExpression(kind1) && IsBooleanLiteralExpression(kind2) && kind1 != kind2) { if (options.UseExpression) { return(new IfElseToAssignmentWithConditionAnalysis(ifStatement, left1, condition, semanticModel, negate: kind1 == SyntaxKind.FalseLiteralExpression).ToImmutableArray()); } return(Empty); } NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(condition, semanticModel: semanticModel, cancellationToken: cancellationToken); if (nullCheck.Success) { IfAnalysis refactoring = CreateIfToAssignment( ifStatement, left1, (nullCheck.IsCheckingNull) ? right2 : right1, (nullCheck.IsCheckingNull) ? right1 : right2, nullCheck, options, semanticModel, cancellationToken); if (refactoring != null) { return(refactoring.ToImmutableArray()); } } } if (options.UseConditionalExpression && !IsNullLiteralConvertedToNullableOfT(right1, semanticModel, cancellationToken) && !IsNullLiteralConvertedToNullableOfT(right2, semanticModel, cancellationToken)) { return(new IfElseToAssignmentWithConditionalExpressionAnalysis(ifStatement, left1, right1, right2, semanticModel).ToImmutableArray()); } return(Empty); }
public virtual ExpressionStatementSyntax Visit(ExpressionStatementSyntax expressionStatement) { var returnInvocation = (InvocationExpressionSyntax)expressionStatement.Expression; var returnMember = (MemberAccessExpressionSyntax)returnInvocation.Expression; returnMember = returnMember.WithName(SyntaxFactory.IdentifierName("Returns")); var callInvocation = (InvocationExpressionSyntax)returnMember.Expression; var argument = callInvocation.ArgumentList.Arguments[0].Expression; if (argument is MemberAccessExpressionSyntax argumentMember) { var identifier = (IdentifierNameSyntax)argumentMember.Expression; identifier = SyntaxFactory.IdentifierName(identifier + "Mock"); var setupMember = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, identifier, SyntaxFactory.IdentifierName("Setup")); var lambdaParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier("s")); var setupLambda = SyntaxFactory.SimpleLambdaExpression(lambdaParameter, argumentMember.WithExpression(SyntaxFactory.IdentifierName("s"))); var setupInvocation = SyntaxFactory.InvocationExpression(setupMember, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(setupLambda) }))); returnMember = returnMember.WithExpression(setupInvocation); returnInvocation = returnInvocation.WithExpression(returnMember); expressionStatement = expressionStatement.WithExpression(returnInvocation); } else if (argument is InvocationExpressionSyntax argumentInvo) { var argumentMember1 = (MemberAccessExpressionSyntax)argumentInvo.Expression; var identifier = (IdentifierNameSyntax)argumentMember1.Expression; identifier = SyntaxFactory.IdentifierName(identifier + "Mock"); var setupMember = SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, identifier, SyntaxFactory.IdentifierName("Setup")); var lambdaParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier("s")); argumentInvo = argumentInvo.WithExpression(argumentMember1.WithExpression(SyntaxFactory.IdentifierName("s"))); var setupLambda = SyntaxFactory.SimpleLambdaExpression(lambdaParameter, argumentInvo); var setupInvocation = SyntaxFactory.InvocationExpression(setupMember, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] { SyntaxFactory.Argument(setupLambda) }))); returnMember = returnMember.WithExpression(setupInvocation); returnInvocation = returnInvocation.WithExpression(returnMember); expressionStatement = expressionStatement.WithExpression(returnInvocation); } return(expressionStatement); }
protected override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node) { ExpressionSyntax expression = RewritePostfixUnarys (node.Expression); if (expression != node.Expression) node = node.Update (expression, node.SemicolonToken); return base.VisitExpressionStatement (node); }
public void VisitExpressionStatement(ExpressionStatementSyntax node) { if (node == null) throw new ArgumentNullException("node"); node.Validate(); WriteLeadingTrivia(node); _writer.WriteIndent(); node.Expression.Accept(this); _writer.EndStatement(); WriteTrailingTrivia(node); }
public void Flatten(ExpressionStatementSyntax node, List<FlatStatement> instructions) { FlatOperand into_lvalue = null; ResolveExpression(node.Expression, into_lvalue, instructions); // nothing else to do }
private BoundExpressionStatement BindExpressionStatement(ExpressionStatementSyntax syntax) { return(new BoundExpressionStatement(Bind(syntax.Expression, BindExpression))); }
/// <summary> /// /// </summary> /// <param name="node"></param> /// <remarks> /// Statements will cause an AST walker to be created, thus we don't need to go further deeper in the /// tree by visiting the node. /// </remarks> public override void VisitExpressionStatement(ExpressionStatementSyntax node) { this.VisitStatement(node); }
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { base.VisitExpressionStatement(node); counter++; }
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { CreateConnectedEndNode(node); }
public virtual void VisitExpressionStatement(ExpressionStatementSyntax node) { DefaultVisit(node); }
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { AddExpressionTerms(node.Expression, _expressions); }
public BoundExpressionStatement(ExpressionStatementSyntax syntax, BoundExpression expression) : base(BoundNodeKind.ExpressionStatement, syntax) { Expression = expression; }
private bool IsCall(ExpressionStatementSyntax statement, SemanticModel semanticModel) => statement.Expression is InvocationExpressionSyntax i && IsCall(i, semanticModel);
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { Emit <ExpressionBlock, ExpressionStatementSyntax>(node); }
private static ConstructorDeclarationSyntax UpdateConstructor(ConstructorDeclarationSyntax constructor, ParameterSyntax parameter, ExpressionStatementSyntax assignment) { var constructorWithParams = constructor.AddParameterListParameters(parameter); var body = constructorWithParams.Body ?? Block(); var newBody = body.Statements.Insert(0, assignment); return(constructorWithParams .WithBody(body.WithStatements(newBody)) .WithLeadingTrivia(constructor.GetLeadingTrivia()) .WithTrailingTrivia(constructor.GetTrailingTrivia())); }
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { Visit(node.Expression, _enclosing); }
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); }
private bool TryCheckVariableAndIfStatementForm( SyntaxNodeAnalysisContext syntaxContext, IfStatementSyntax ifStatement, BinaryExpressionSyntax condition, ExpressionStatementSyntax expressionStatement, InvocationExpressionSyntax invocationExpression, DiagnosticSeverity severity) { 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) }; ReportDiagnostics(syntaxContext, localDeclarationStatement, ifStatement, expressionStatement, severity, additionalLocations, Constants.VariableAndIfStatementForm); return(true); }
/// <summary> /// コンストラクタ /// </summary> /// <param name="method">メソッドインスタンス</param> /// <param name="statement">構文インスタンス</param> public ExpressionStatement(IMethod method, ExpressionStatementSyntax statement) : base(method, statement) { }
private static async Task <Document> ApplyFixAsync(CodeFixContext context, CancellationToken cancellationToken, ExpressionStatementSyntax statement, IFieldSymbol field, bool usesUnderscoreNames) { var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken) .ConfigureAwait(false); var block = statement.FirstAncestor <BlockSyntax>(); if (block?.Statements != null) { var index = block.Statements.IndexOf(statement); if (index > 0 && block.Statements[index - 1] is ExpressionStatementSyntax expressionStatement && expressionStatement.Expression is AssignmentExpressionSyntax assignment && assignment.Right is ObjectCreationExpressionSyntax objectCreation) { if ((assignment.Left is IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == field.Name) || (assignment.Left is MemberAccessExpressionSyntax memberAccess && memberAccess.Expression is ThisExpressionSyntax && memberAccess.Name.Identifier.ValueText == field.Name)) { editor.RemoveNode(statement); if (objectCreation.Initializer != null) { editor.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, statement.Expression)); return(editor.GetChangedDocument()); } editor.ReplaceNode( objectCreation, objectCreation.WithInitializer( SyntaxFactory.InitializerExpression( SyntaxKind.CollectionInitializerExpression, SyntaxFactory.SingletonSeparatedList(statement.Expression)) .WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation))); return(editor.GetChangedDocument()); } } } var memberAccessExpressionSyntax = usesUnderscoreNames ? (MemberAccessExpressionSyntax)editor .Generator.MemberAccessExpression( SyntaxFactory.IdentifierName(field.Name), "Add") : (MemberAccessExpressionSyntax)editor.Generator.MemberAccessExpression( editor.Generator.MemberAccessExpression( SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName(field.Name)), "Add"); editor.ReplaceNode( statement, SyntaxFactory.ExpressionStatement( (InvocationExpressionSyntax)editor.Generator.InvocationExpression( memberAccessExpressionSyntax, statement.Expression))); return(editor.GetChangedDocument()); }
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); }
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { base.VisitExpressionStatement(node); _builder.Append(node.SemicolonToken.ToString()); }
public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node) { var expressionCheck = node.Expression; bool and = (expressionCheck.Kind() == SyntaxKind.AndAssignmentExpression); bool or = (expressionCheck.Kind() == SyntaxKind.OrAssignmentExpression); bool sub = (expressionCheck.Kind() == SyntaxKind.SubtractAssignmentExpression); bool add = (expressionCheck.Kind() == SyntaxKind.AddAssignmentExpression); bool mult = (expressionCheck.Kind() == SyntaxKind.MultiplyAssignmentExpression); bool div = (expressionCheck.Kind() == SyntaxKind.DivideAssignmentExpression); bool rightShift = (expressionCheck.Kind() == SyntaxKind.RightShiftAssignmentExpression); bool leftShift = (expressionCheck.Kind() == SyntaxKind.LeftShiftAssignmentExpression); bool xor = (expressionCheck.Kind() == SyntaxKind.ExclusiveOrAssignmentExpression); bool modulo = (expressionCheck.Kind() == SyntaxKind.ModuloAssignmentExpression); bool condition = and || or || sub || add || mult || div || rightShift || leftShift || xor || modulo; if (!condition) { return(node); } SyntaxKind newOperation = SyntaxKind.AddExpression; if (and) { newOperation = SyntaxKind.BitwiseAndExpression; } else if (or) { newOperation = SyntaxKind.BitwiseOrExpression; } else if (sub) { newOperation = SyntaxKind.SubtractExpression; } else if (add) { newOperation = SyntaxKind.AddExpression; } else if (mult) { newOperation = SyntaxKind.MultiplyExpression; } else if (div) { newOperation = SyntaxKind.DivideExpression; } else if (leftShift) { newOperation = SyntaxKind.LeftShiftExpression; } else if (rightShift) { newOperation = SyntaxKind.RightShiftExpression; } else if (xor) { newOperation = SyntaxKind.ExclusiveOrExpression; } else if (modulo) { newOperation = SyntaxKind.ModuloExpression; } var expression = expressionCheck as AssignmentExpressionSyntax; var left = expression.Left.WithoutTrivia(); var right = expression.Right.WithoutTrivia(); var newRight = SyntaxFactory.BinaryExpression(newOperation, left, right); var assignment = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, left, newRight); var newExpression = SyntaxFactory.ExpressionStatement(assignment) .NormalizeWhitespace().WithTriviaFrom(node); return(newExpression); }
private SyntaxNode MutateUnaryStatement(ExpressionStatementSyntax expressionStatement, MutationContext context) { var expressionCopy = expressionStatement.TrackNodes(expressionStatement, expressionStatement.Expression); return(MutateSubExpressionWithIfStatements(expressionStatement, expressionCopy, expressionStatement.Expression, context)); }
public static void WriteStatement(HaxeWriter writer, ExpressionStatementSyntax statement) { writer.WriteIndent(); Write(writer, statement.Expression); writer.Write(";\r\n"); }
public override Evaluation VisitExpressionStatement(ExpressionStatementSyntax node) { node.Expression?.Accept <Evaluation>(this); return(base.VisitExpressionStatement(node)); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { if (!Settings.IsAnyCodeFixEnabled( CodeFixIdentifiers.UseYieldReturnInsteadOfReturn, CodeFixIdentifiers.RemoveReturnKeyword, CodeFixIdentifiers.RemoveReturnExpression, CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression)) { return; } SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); if (!TryFindFirstAncestorOrSelf(root, context.Span, out ReturnStatementSyntax returnStatement)) { return; } foreach (Diagnostic diagnostic in context.Diagnostics) { switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.CannotReturnValueFromIterator: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.UseYieldReturnInsteadOfReturn)) { break; } ExpressionSyntax expression = returnStatement.Expression; if (expression != null) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ISymbol containingSymbol = semanticModel.GetEnclosingSymbol(returnStatement.SpanStart, context.CancellationToken); if (containingSymbol?.Kind == SymbolKind.Method) { var methodSymbol = (IMethodSymbol)containingSymbol; ITypeSymbol returnType = methodSymbol.ReturnType; var replacementKind = SyntaxKind.None; if (returnType.SpecialType == SpecialType.System_Collections_IEnumerable) { if (semanticModel .GetTypeSymbol(expression, context.CancellationToken) .OriginalDefinition .IsIEnumerableOrIEnumerableOfT()) { replacementKind = SyntaxKind.ForEachStatement; } else { replacementKind = SyntaxKind.YieldReturnStatement; } } else if (returnType.Kind == SymbolKind.NamedType) { var namedTypeSymbol = (INamedTypeSymbol)returnType; if (namedTypeSymbol.OriginalDefinition.IsIEnumerableOfT()) { if (semanticModel.IsImplicitConversion(expression, namedTypeSymbol.TypeArguments[0])) { replacementKind = SyntaxKind.YieldReturnStatement; } else { replacementKind = SyntaxKind.ForEachStatement; } } } if (replacementKind == SyntaxKind.YieldReturnStatement || (replacementKind == SyntaxKind.ForEachStatement && !returnStatement.SpanContainsDirectives())) { CodeAction codeAction = CodeAction.Create( "Use yield return instead of return", cancellationToken => UseYieldReturnInsteadOfReturnRefactoring.RefactorAsync(context.Document, returnStatement, replacementKind, semanticModel, cancellationToken), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } } } break; } case CompilerDiagnosticIdentifiers.SinceMethodReturnsVoidReturnKeywordMustNotBeFollowedByObjectExpression: case CompilerDiagnosticIdentifiers.SinceMethodIsAsyncMethodThatReturnsTaskReturnKeywordMustNotBeFollowedByObjectExpression: { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); if (Settings.IsCodeFixEnabled(CodeFixIdentifiers.ChangeMemberTypeAccordingToReturnExpression)) { ChangeMemberTypeRefactoring.ComputeCodeFix(context, diagnostic, returnStatement.Expression, semanticModel); } if (Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveReturnExpression)) { ISymbol symbol = semanticModel.GetEnclosingSymbol(returnStatement.SpanStart, context.CancellationToken); if (symbol?.Kind == SymbolKind.Method) { var methodSymbol = (IMethodSymbol)symbol; if (methodSymbol.ReturnsVoid || methodSymbol.ReturnType.Equals(semanticModel.GetTypeByMetadataName(MetadataNames.System_Threading_Tasks_Task))) { CodeAction codeAction = CodeAction.Create( "Remove return expression", cancellationToken => { ReturnStatementSyntax newNode = returnStatement .WithExpression(null) .WithFormatterAnnotation(); return(context.Document.ReplaceNodeAsync(returnStatement, newNode, cancellationToken)); }, GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemoveReturnExpression)); context.RegisterCodeFix(codeAction, diagnostic); } } } if (Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveReturnKeyword)) { ExpressionSyntax expression = returnStatement.Expression; if (expression.IsKind( SyntaxKind.InvocationExpression, SyntaxKind.ObjectCreationExpression, SyntaxKind.PreDecrementExpression, SyntaxKind.PreIncrementExpression, SyntaxKind.PostDecrementExpression, SyntaxKind.PostIncrementExpression) || expression is AssignmentExpressionSyntax) { CodeAction codeAction = CodeAction.Create( "Remove 'return'", cancellationToken => { SyntaxTriviaList leadingTrivia = returnStatement .GetLeadingTrivia() .AddRange(returnStatement.ReturnKeyword.TrailingTrivia.EmptyIfWhitespace()) .AddRange(expression.GetLeadingTrivia().EmptyIfWhitespace()); ExpressionStatementSyntax newNode = SyntaxFactory.ExpressionStatement( expression.WithLeadingTrivia(leadingTrivia), returnStatement.SemicolonToken); return(context.Document.ReplaceNodeAsync(returnStatement, newNode, cancellationToken)); }, GetEquivalenceKey(diagnostic, CodeFixIdentifiers.RemoveReturnKeyword)); context.RegisterCodeFix(codeAction, diagnostic); } } break; } } } }
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { base.VisitExpressionStatement(node); // Get the first syntax node. foreach (SyntaxNode child in node.ChildNodes()) { // Operations are of invocation expression kind. if (child.IsKind(SyntaxKind.InvocationExpression)) { InvocationExpressionSyntax expr = child as InvocationExpressionSyntax; string exprText = expr.Expression.ToString(); // Split the expression on the dot token. string[] exprTokens = exprText.Split('.'); //Debug.Assert(exprTokens.Length == 2, "Nested member access."); // Add the last token as the operation. macroOperations.Add(exprTokens[exprTokens.Length - 1]); } } }
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { }
public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node) { SyntaxNode updatedNode = base.VisitExpressionStatement(node); if (node.Expression.Kind == SyntaxKind.AssignExpression) { if (node.Parent.Kind == SyntaxKind.Block) { // There is a parent block so it is ok to remove the statement completely. updatedNode = null; } else { // The parent context is some statement like an if statement without a block. // Return an empty statement. updatedNode = Syntax.EmptyStatement() .WithLeadingTrivia(updatedNode.GetLeadingTrivia()) .WithTrailingTrivia(updatedNode.GetTrailingTrivia()); } } return updatedNode; }
public ExpressionStatementTranslation(ExpressionStatementSyntax syntax, SyntaxTranslation parent) : base(syntax, parent) { Expression = syntax.Expression.Get <ExpressionTranslation>(this); }
public override void VisitExpressionStatement(ExpressionStatementSyntax node) { base.VisitExpressionStatement(node); }
protected abstract void CompileExpressionStatement(ExpressionStatementSyntax statement);