private bool IsInvocationAFluentMethod(InvocationExpressionSyntax invocation) { return(IsInvocationAModuleCtor(invocation?.DescendantNodes() .TakeWhile(x => x is InvocationExpressionSyntax || x is MemberAccessExpressionSyntax) .OfType <InvocationExpressionSyntax>() .LastOrDefault())); }
private static async Task <Document> FixInteropAPI(Document document, SyntaxNode root, InvocationExpressionSyntax invocationExpressionSyntax, string apiId, CancellationToken cancellationToken) { var mappedApi = WinUIInteropAnalyzer.UWPToWinUIInteropAPIMap[apiId] !.Value; if (!mappedApi.HasValue) { var comment = await CSharpSyntaxTree.ParseText(@$ " /* TODO: This api is not supported in Windows App SDK yet. Read: https://docs.microsoft.com/en-us/windows/apps/windows-app-sdk/migrate-to-windows-app-sdk/what-is-supported */ ", cancellationToken : cancellationToken).GetRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = root !.ReplaceNode <SyntaxNode>(invocationExpressionSyntax, invocationExpressionSyntax.WithLeadingTrivia(comment.GetLeadingTrivia())); return(document.WithSyntaxRoot(newRoot)); } var(newTypeNamespace, newTypeName, newMethodName) = mappedApi !.Value; var documentEditor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var argsToAdd = invocationExpressionSyntax.DescendantNodes().OfType <ArgumentListSyntax>().First().Arguments.ToArray(); var newExpressionRoot = await CSharpSyntaxTree.ParseText(@$ " {newTypeNamespace}.{newTypeName}.{newMethodName}(App.WindowHandle)
private async Task <Document> ConvertToInterpolated(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { SyntaxNode sn = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); InvocationExpressionSyntax ies = sn.FindNode(diagnostic.Location.SourceSpan) .DescendantNodesAndSelf(null, false) .OfType <InvocationExpressionSyntax>().First(); var argumentList = ies.DescendantNodes(null, false) .Where(x => Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(x) == SyntaxKind.ArgumentList).ToList()[0]; var arguments = argumentList.DescendantNodes(null, false) .Where(x => Microsoft.CodeAnalysis.CSharp.CSharpExtensions.Kind(x) == SyntaxKind.Argument && x.Parent == argumentList) .ToList(); StringBuilder sb = new StringBuilder("$" + arguments[0]); for (int i = 1; i < arguments.Count; ++i) { var old = string.Format("{{{0}}}", Convert.ToString(i - 1)); var newString = string.Format("{{{0}}}", Convert.ToString(arguments[i])); if (newString.Contains("?")) { newString = $"{{({newString.TrimStart('{').TrimEnd('}')})}}"; } sb = sb.Replace(old, newString); } SourceText st = (await document.GetTextAsync(cancellationToken)).Replace(ies.Span, sb.ToString()); return(document.WithText(st)); }
static bool ValidateInvocation(InvocationExpressionSyntax expr) { // Okay => x = M(), var x = M(), return M(), from x in M(), (bool) ? M() : M() if (expr.Parent.IsKind(SyntaxKind.SimpleAssignmentExpression)) { return(true); } if (expr.Parent.IsKind(SyntaxKind.EqualsValueClause) && expr.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator)) { return(true); } if (expr.Parent.IsKind(SyntaxKind.ReturnStatement)) { return(true); } if (expr.Parent.IsKind(SyntaxKind.FromClause)) { return(true); } if (expr.Parent.IsKind(SyntaxKind.ConditionalExpression)) { return(true); } // Okay => M().M() if (expr.DescendantNodes().OfType <InvocationExpressionSyntax>().Any()) { return(true); } return(false); }
public void TestGetSyntaxNodesFromIdentifierFunc() { string code1 = "public class TestCLass{public void Main(){Test(\"test\");} public void Test(){} public void Test(string param){}}"; SyntaxTree tree1 = CSharpSyntaxTree.ParseText(code1); InvocationExpressionSyntax node1 = tree1.GetRootAsync().Result.DescendantNodesAndSelf().OfType <InvocationExpressionSyntax>().First(); MethodDeclarationSyntax node2 = tree1.GetRootAsync().Result.DescendantNodesAndSelf().OfType <MethodDeclarationSyntax>().ElementAt(1); MethodDeclarationSyntax node3 = tree1.GetRootAsync().Result.DescendantNodesAndSelf().OfType <MethodDeclarationSyntax>().Last(); IdentifierNameSyntax node4 = node1.DescendantNodes().OfType <IdentifierNameSyntax>().Last(); List <SyntaxTree> trees1 = new List <SyntaxTree> { tree1 }; Compilation comp1 = CSharpCompilation.Create("TestCompilation1", trees1); ScriptAnalyzerSymbolHelper sHelper = new ScriptAnalyzerSymbolHelper(new Compilation[] { comp1 }); ScriptAnalyzerResourceHelper rHelper = new ScriptAnalyzerResourceHelper(sHelper); List <SyntaxNode> result = rHelper.GetSyntaxNodes(node4); Assert.IsNotNull(result, "Returns a list"); Assert.AreEqual(1, result.Count(), "List has one node"); CollectionAssert.Contains(result, node3, "Node is expected node"); CollectionAssert.DoesNotContain(result, node2, "Node is not other unused function"); }
private static void CheckForCondition(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocationNode, SyntaxNode expressionStatementParent, DiagnosticDescriptor descriptor) { if ((!expressionStatementParent?.DescendantNodesAndTokens()?.Any(_ => _.IsKind(SyntaxKind.EqualsToken)) ?? false) && !(invocationNode.DescendantNodes()?.Any(_ => new ContainsInvocationExpressionWalker(_).HasIssue) ?? false)) { context.ReportDiagnostic(Diagnostic.Create(descriptor, invocationNode.GetLocation())); } }
private bool ContainsCallsWithSideEffects(InvocationExpressionSyntax invocation) { return(invocation .DescendantNodes() .OfType <InvocationExpressionSyntax>() .Select(GetIdentifierName) .Any(text => text != null && sideEffectWords.Overlaps(text.SplitCamelCaseToWords()))); }
private bool ContainsCallsWithSideEffects(InvocationExpressionSyntax invocation) { return(invocation .DescendantNodes() .OfType <InvocationExpressionSyntax>() .Select(GetIdentifierName) .Any(name => !string.IsNullOrEmpty(name) && name != "SetEquals" && sideEffectWords.Contains(name.SplitCamelCaseToWords().First()))); }
public static SyntaxNode RetrieveMethodOwningObject(InvocationExpressionSyntax invocation) { var expression = invocation.DescendantNodes().OfType <MemberAccessExpressionSyntax>().FirstOrDefault()?.Expression; if (expression == null) { return(null); } return(FindDeclearationNode(expression.GetLocation())); }
public override void VisitInvocationExpression(InvocationExpressionSyntax node) { var detections = node.DescendantNodes() .OfType <IdentifierNameSyntax>() .Where(n => WeakHashAlgorithms.Any(a => n.Identifier.Text.IndexOf(a) >= 0)); foreach (IdentifierNameSyntax identifier in detections) { this.ReportableItems.Add(new AnalyserItem(ReporterMessage, node.GetReference())); } }
private static void CheckForCondition(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocationNode, SyntaxNode 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())); } }
static bool ValidateInvocation(InvocationExpressionSyntax expr) { // Okay => x = M(), var x = M(), return M(), from x in M(), (bool) ? M() : M() if (expr.Parent.IsKind(SyntaxKind.SimpleAssignmentExpression)) return true; if (expr.Parent.IsKind(SyntaxKind.EqualsValueClause) && expr.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator)) return true; if (expr.Parent.IsKind(SyntaxKind.ReturnStatement)) return true; if (expr.Parent.IsKind(SyntaxKind.FromClause)) return true; if (expr.Parent.IsKind(SyntaxKind.ConditionalExpression)) return true; // Okay => M().M() if (expr.DescendantNodes().OfType<InvocationExpressionSyntax>().Any()) return true; return false; }
private StatementSyntax LinkOperand(ExpressionSyntax operand, InvocationExpressionSyntax success, InvocationExpressionSyntax failure, Dictionary <string, TypeSyntax> assignments) { if (operand is InvocationExpressionSyntax) { return(LinkProcessInvocation(operand as InvocationExpressionSyntax, success, failure)); } if (operand is IdentifierNameSyntax) { return(LinkSignal(operand as IdentifierNameSyntax, success, failure)); } if (operand is AssignmentExpressionSyntax) { return(LinkAssignment(operand as AssignmentExpressionSyntax, success, failure, assignments)); } if (operand is ParenthesizedExpressionSyntax) { return(LinkOperand((operand as ParenthesizedExpressionSyntax).Expression, success, failure, assignments)); } if (operand is LiteralExpressionSyntax) { var literal = operand as LiteralExpressionSyntax; switch (literal.Kind()) { case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: return(CSharp.ExpressionStatement(success .ReplaceNodes(success .DescendantNodes() .OfType <LiteralExpressionSyntax>() .Where(l => l.Kind() == SyntaxKind.TrueLiteralExpression || l.Kind() == SyntaxKind.FalseLiteralExpression), (on, nn) => literal))); } } throw new NotImplementedException(); //td: }
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node) { if (Fields != null) { return(node); } var mae = node.Expression as MemberAccessExpressionSyntax; if (mae == null) { return(Visit(node.Expression)); } if (KnonwMethodsToInsepct.Contains(mae.Name.Identifier.Text) == false) { return(Visit(node.Expression)); } var last = node.DescendantNodes(descendIntoChildren: syntaxNode => { if (syntaxNode is AnonymousObjectCreationExpressionSyntax) { return(false); } return(true); }) .LastOrDefault(x => x.IsKind(SyntaxKind.AnonymousObjectCreationExpression)) as AnonymousObjectCreationExpressionSyntax; if (last != null) { VisitAnonymousObjectCreationExpression(last); } else { ThrowIndexingFunctionMustReturnAnonymousObject(); } return(node); }
private static ObjectCreationExpressionSyntax GetObjectCreation(InvocationExpressionSyntax invocation, SemanticModel semanticModel) { var accessRuleSyntaxNode = GetVulnerableFileSystemAccessRule(invocation.DescendantNodes()); if (accessRuleSyntaxNode != null) { return(accessRuleSyntaxNode); } var accessRuleSymbol = invocation.GetArgumentSymbolsOfKnownType(KnownType.System_Security_AccessControl_FileSystemAccessRule, semanticModel).FirstOrDefault(); if (accessRuleSymbol == null || accessRuleSymbol is IMethodSymbol) { return(null); } return(GetVulnerableFileSystemAccessRule(accessRuleSymbol.GetLocationNodes(invocation))); ObjectCreationExpressionSyntax GetVulnerableFileSystemAccessRule(IEnumerable <SyntaxNode> nodes) => nodes.OfType <ObjectCreationExpressionSyntax>() .FirstOrDefault(objectCreation => IsFileSystemAccessRuleForEveryoneWithAllow(objectCreation, semanticModel)); }
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node) { if (Fields != null) { return(node); } var last = node.DescendantNodes(descendIntoChildren: syntaxNode => true) .LastOrDefault(x => x.IsKind(SyntaxKind.AnonymousObjectCreationExpression)) as AnonymousObjectCreationExpressionSyntax; if (last == null) { return(node); } // check if maybe we are nested var parent = last.Ancestors(ascendOutOfTrivia: true) .FirstOrDefault(x => x.IsKind(SyntaxKind.AnonymousObjectCreationExpression)) as AnonymousObjectCreationExpressionSyntax; Fields = RewritersHelper.ExtractFields(parent ?? last); return(node); }
public override void VisitInvocationExpression(InvocationExpressionSyntax node) { var identifierNames = node.DescendantNodes() .OfType <SimpleNameSyntax>() .ToList(); if (identifierNames.Count < 2) { return; } if (identifierNames[0].Identifier.Text != _variableName) { return; } if (identifierNames[1].Identifier.Text != "Add") { IsAllParametersStatic = false; return; } if (node.ArgumentList.Arguments.Count < 1) { return; } if (!(node.ArgumentList.Arguments[0].Expression is LiteralExpressionSyntax literalExpression)) { IsAllParametersStatic = false; return; } SqlParameters.Add(literalExpression.Token.ValueText); }
static bool ValidateInvocation(InvocationExpressionSyntax expr) { bool allAncestorsIsParenthes = true; foreach (var x in expr.Ancestors()) { // scope is in lambda, method if (x.IsKind(SyntaxKind.SimpleLambdaExpression) || x.IsKind(SyntaxKind.ParenthesizedLambdaExpression) || x.IsKind(SyntaxKind.ArrowExpressionClause)) { // () => M() if (allAncestorsIsParenthes) return true; break; } if (x.IsKind(SyntaxKind.MethodDeclaration)) break; if (x.IsKind(SyntaxKind.PropertyDeclaration)) break; if (x.IsKind(SyntaxKind.ConstructorDeclaration)) break; // x = M() if (x.IsKind(SyntaxKind.SimpleAssignmentExpression)) return true; // var x = M() if (x.IsKind(SyntaxKind.VariableDeclarator)) return true; // return M() if (x.IsKind(SyntaxKind.ReturnStatement)) return true; // from x in M() if (x.IsKind(SyntaxKind.FromClause)) return true; // (bool) ? M() : M() if (x.IsKind(SyntaxKind.ConditionalExpression)) return true; // M(M()) if (x.IsKind(SyntaxKind.InvocationExpression)) return true; // new C(M()) if (x.IsKind(SyntaxKind.ObjectCreationExpression)) return true; // (((((M())))) if (!x.IsKind(SyntaxKind.ParenthesizedExpression)) { allAncestorsIsParenthes = false; } } // Okay => M().M() if (expr.DescendantNodes().OfType<InvocationExpressionSyntax>().Any()) return true; return false; }
private SyntaxNode GetMethodName(InvocationExpressionSyntax invocation) { // The left parentheses is the rightmost position for the method name. int rightMost = invocation.ArgumentList.OpenParenToken.Span.Start; // Order the decendents by its span var orderedDecendents = invocation.DescendantNodes().OrderBy(n => n.Span.Length); // The decendent whose length is the most and end is before ( should be method name node. return orderedDecendents.Last(n => n.Span.End <= rightMost); }
static bool ValidateInvocation(InvocationExpressionSyntax expr) { bool allAncestorsIsParenthes = true; foreach (var x in expr.Ancestors()) { // scope is in lambda, method if (x.IsKind(SyntaxKind.SimpleLambdaExpression) || x.IsKind(SyntaxKind.ParenthesizedLambdaExpression) || x.IsKind(SyntaxKind.ArrowExpressionClause)) { // () => M() if (allAncestorsIsParenthes) { return(true); } break; } if (x.IsKind(SyntaxKind.MethodDeclaration)) { break; } if (x.IsKind(SyntaxKind.PropertyDeclaration)) { break; } if (x.IsKind(SyntaxKind.ConstructorDeclaration)) { break; } // x = M() if (x.IsKind(SyntaxKind.SimpleAssignmentExpression)) { return(true); } // var x = M() if (x.IsKind(SyntaxKind.VariableDeclarator)) { return(true); } // return M() if (x.IsKind(SyntaxKind.ReturnStatement)) { return(true); } // from x in M() if (x.IsKind(SyntaxKind.FromClause)) { return(true); } // (bool) ? M() : M() if (x.IsKind(SyntaxKind.ConditionalExpression)) { return(true); } // M(M()) if (x.IsKind(SyntaxKind.InvocationExpression)) { return(true); } // new C(M()) if (x.IsKind(SyntaxKind.ObjectCreationExpression)) { return(true); } // (((((M())))) if (!x.IsKind(SyntaxKind.ParenthesizedExpression)) { allAncestorsIsParenthes = false; } } // Okay => M().M() if (expr.DescendantNodes().OfType <InvocationExpressionSyntax>().Any()) { return(true); } return(false); }