0

I've extracted all InvocationExpressionSyntax's from a parsed C# script with results like:

1. System.IO.Directory.GetDirectories(@"c:\").First()
2. Math.Sin(3).ToString()
3. value.Substring(0, 1)

I also have the SemanticModel object and have searched and experimented in various ways to do the following:

  1. Iterate from the last to the first invocation call and determine which CLR type it belongs to. As an example, Math.Sin(3).ToString() should tell me that the method is ToString while the type is Double. In the next iteration the method would be Sin and the Type would be Math.
  2. In order to do the above, I have a hard-coded list of types List<Type> Allowed. I now want to extract the CLR Type of each segment of the InvocationExpressionSyntax and see if it is included in the whitelist.

The objective is to white-list types and calls to a small subset that end-users can utilize. Example, Math.XXX is ok, Directory.XXX is not.

I have searched around and experimented quite a bit but have not figured out how to extract a Type object against each expression. Expected types of course are MethodInfo, PropertyInfo and Class.

Any pointers would be appreciated.

Raheel Khan
  • 14,205
  • 13
  • 80
  • 168

1 Answers1

0

Have you considered using the NDepend code querying model? https://www.ndepend.com/features/cqlinq#CQL https://www.ndepend.com/docs/cqlinq-features https://www.ndepend.com/docs/cqlinq-syntax

For example you can write the code query:

let blackListedMethodNames = new [] {
  "System.IO.Directory.XXX",
  ...
}.ToHashSet()

let blackListedMethods =
Methods.Where(m => blackListedMethodNames.Contains(m.FullName)).ToHashSet()

from m in Application.Methods.UsingAny(blackListedMethods )
select new { m, 
             blackListedMethodsCalled = m.MethodsCalled.Intersect(blackListedMethods ) }

for example:

NDepend code query to black list some method

Patrick from NDepend team
  • 13,237
  • 6
  • 61
  • 92