0

First off, I am HORRIBLE with Regex. Apologies up front if this is dead easy and I'm just missing it :(

Ok, so let's say I'm looking to parse my source code, and find all of my private functions. Further, let's say I want to get that entire block of code so I can examine it.

Regex match of:

Private Function[\s\S]*?End Function

works great.

Now, what if I want to find all functions that are missing a Return statement? I can not seem to figure this one out (see above re: regex and I don't get along famously).

Anyone mind pointing me in the right direction? I'm using .NET implementation of regex if that matters (and it seems to - none of the Java examples I find seem to work!)

I'm using regexstorm.net for my testing, if it matters :) Thanks!

John
  • 921
  • 1
  • 9
  • 24
  • why dont you just use your above regex, then foreach match, check if the captured string contains `return`? That'll be pretty accurate and pretty easy. – Jonesopolis May 01 '16 at 01:07

1 Answers1

0

It looks like you might be analyzing Visual Basic. You could use Microsoft's Code Analysis tools (Roslyn) in order parse the code and analyze the different parts. This will prevent having to look for varying syntax acceptance of different code files. The following sample code will determine if a Function is private or has an as clause.

string code = @"
    Function MyFunction()
    End Function

    Private Function MyPrivateFunction()
    End Function

    Function WithAsClause() As Integer
    End Function
    ";

// Parse the code file.
var tree = VisualBasicSyntaxTree.ParseText(code);

var root = tree.GetCompilationUnitRoot();

// Find all functions in the code file.
var nodes = root.DescendantNodes()
    .Where(n => n.Kind() == SyntaxKind.FunctionBlock)
    .Cast<MethodBlockSyntax>();

foreach (var node in nodes)
{
    // Analyze the data for the function.
    var functionName = node.SubOrFunctionStatement.Identifier.GetIdentifierText();
    bool isPrivate = node.BlockStatement.Modifiers.Any(m => m.Kind() == SyntaxKind.PrivateKeyword);
    var asClause = node.SubOrFunctionStatement.AsClause;
    bool hasAsClause = asClause != null;

    Console.WriteLine($"{functionName}\t{isPrivate}\t{hasAsClause}");
}
joncloud
  • 757
  • 5
  • 14
  • Ok... that.. is friggin' cool, I won't lie. Thanks, I had no idea this even existed!! – John May 01 '16 at 02:13
  • Depending upon what your project requirements are you can also automate updating the code too with the same framework. – joncloud May 01 '16 at 02:14